Here's a sample solution for Sliding Window Maximum problem in Java.
Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can only
see the k numbers in the window. Each time the sliding window moves
right by one position.
I want to get the time and space complexity of this function. Here's what I think would be the answer:
Time: O((n-k)(k * logk)) == O(nklogk)
Space (auxiliary): O(n) for return int[] and O(k) for pq. Total of O(n).
Is this correct?
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || a.length == 0) return new int[] {};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
// max heap
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int[] result = new int[a.length - k + 1];
int count = 0;
// time: n - k times
for (int i = 0; i < a.length - k + 1; i++) {
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
// logk
result[count] = pq.poll();
count = count + 1;
pq.clear();
}
return result;
}
You're right in most of the part except -
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
Here total number of executions is log1 + log2 + log3 + log4 + ... + logk. The summation of this series -
log1 + log2 + log3 + log4 + ... + logk = log(k!)
And second thought is, you can do it better than your linearithmic time solution using double-ended queue property which will be O(n). Here is my solution -
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) {
return new int[0];
}
int n = nums.length;
int[] result = new int[n - k + 1];
int indx = 0;
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k + 1) {
q.poll();
}
// remove smaller numbers in k range as they are useless
while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
q.pollLast();
}
q.offer(i);
if (i >= k - 1) {
result[indx++] = nums[q.peek()];
}
}
return result;
}
HTH.
Related
I tried to find the time complexity of the following two functions:
the first one
public static int myMethod1(int[] arr) {
int x = 0;
for (int i = 0; i < arr.length / 2; i++) {
for (int j = 0; j < arr.length; j++) {
for (int k = 0; k < arr.length; k++) {
x++;
if (k == arr.length / 2) {
break;
}
}
}
}
return x;
}
So with this one i am thinking.
The method contains 3 loops, and the loops are iterating over variable i, j and k…
i and j, and k are both incremented by 1 for each passing… this gives us as N For each LOOP which leaves us with three N’s.., which gives is O(N^3)
The next one is:
public static int myMethod(int N) {
int x = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N / 2; j++) {
for (int k = 1; k < N;) {
x++;
k *= 2;
}
}
}
return x;
}
With this i am thinking.
The method contains 3 loops, and the loops are iterating over variable i, j and k… i and j are both incremented by 1 for each passing… this gives us as N For each LOOP which leaves us with two N’s.. The last loop k doubles, which gives is log(n).
The result of the this problem is therefore O(N^2· log (N))
is this correct? and if it is not, why?
You are right. In both of the questions
This function returns the max char subset sequence. Example input and output are below. Can someone help with time complexity
function shortenString(str) {
let result = str.charAt(0);
for (let i = 1; i< str.length; i++) {
const c = str.charAt(i);
let j = i - 1;
while (j >= 0) {
const charA = result.charAt(j);
const charB = str.charAt(i);
console.log(`comparing ${charA} to ${charB}`);
if (result.charAt(j) < str.charAt(i)) {
result = result.substring(0, j);
}
j--;
}
result = result + str.charAt(i);
}
return result;
}
We can use the Big O notation to calculate its complexity here
If we look at the code we have to main loops - for and while
The for loop will do n iterations.
Meanwhile the while loop will do n(n+1)/2 iterations - which represent the sum of a series of n numbers. Its complexity is give by O(n^2);
Therefor the complexity of the code if n*n^2 = O(n^3)
What is the n queens complexity time by Back Tracking Method?
and what is the count of Queens Position?
With below algorithm :
void queens (index i)
{
index j;
if (promising(i))
if (i == n)
cout << col[1] through col[n];
else
for (j = 1; j <= n; j++) {
col[i + 1] = j;
queens(i + 1);
}
}
bool promising (index i)
{
index k;
bool Switch;
k = 1;
Switch = true ;
while (k < i && switch) {
if (col[i] == col[k] || abs(col[i] – col[k] == i - k))
switch = false;
k++;
}
return Switch;
}
Any suggestion?
I pick the first row and multiply each element by its cofactor,
but in some cases the method is returning nan.
For example,
1 0 0 1
0 2 0 0
0 0 3 0
0 0 0 4
in this case the method returns nan.
Does anyone know what I did wrong?
getDet3 returns determinant of a 3x3 matrix and it works fine.
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_ = 1, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i+j);
}
return det;
}
Well, there are a few mistakes in your code.
1) The initialization of i_ = 1 should be done just before the j loop, otherwise it will keep the old value.
2) The computation of pow(-1, i+j) should only depend on i, since j has the same value every time in that expression (namely, 3).
So, assuming that getDet3 is correct, the mistake is introduced by i_ going out of bounds. As a whole, the code should look like:
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
i_ = 1;
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i);
}
return det;
}
Personally, I find your variable names confusing. If I understand your idea correctly, you expect i_ to have the value j + 1 and j_ to be k < i ? k : k + 1. IMHO, it would have been less confusing to have named them j_p andk_`, or even to just use the equivalent expression.
In any event, you don't reinitialize i_ inside the outer for loop. So it actually just keeps on incrementing, resulting in array indices outside of the array bounds.
Is there a way of modifing the algorithm in
Finding all cycles in undirected graphs
to consider edges as directed and only cycles of length <= k ?
I reply by myself
static void Main(string[] args)
{
int k = 4;
for (int i = 0; i < graph.GetLength(0); i++)
for (int j = 0; j < graph.GetLength(1); j++)
{
findNewCycles(new int[] { graph[i, j] },k);
}
foreach (int[] cy in cycles)
{
string s = "" + cy[0];
for (int i = 1; i < cy.Length; i++)
s += "," + cy[i];
Console.WriteLine(s);
}
}
static void findNewCycles(int[] path, int k)
{
int n = path[0];
int x;
int[] sub = new int[path.Length + 1];
if (path.Length < k + 1)
{
for (int i = 0; i < graph.GetLength(0); i++)
for (int y = 0; y <= 1; y = y + 2)
if (graph[i, y] == n)
// edge referes to our current node
{
x = graph[i, (y + 1) % 2];
if (!visited(x, path))
// neighbor node not on path yet
{
sub[0] = x;
Array.Copy(path, 0, sub, 1, path.Length);
// explore extended path
findNewCycles(sub,k);
}
else if ((path.Length > 2) && (x == path[path.Length - 1]))
// cycle found
{
int[] p = normalize(path);
int[] inv = invert(p);
if (isNew(p) && isNew(inv))
cycles.Add(p);
}
}
}
}
static bool equals(int[] a, int[] b)
{
bool ret = (a[0] == b[0]) && (a.Length == b.Length);
for (int i = 1; ret && (i < a.Length); i++)
if (a[i] != b[i])
{
ret = false;
}
return ret;
}
static int[] invert(int[] path)
{
int[] p = new int[path.Length];
for (int i = 0; i < path.Length; i++)
p[i] = path[path.Length - 1 - i];
return normalize(p);
}
// rotate cycle path such that it begins with the smallest node
static int[] normalize(int[] path)
{
int[] p = new int[path.Length];
int x = smallest(path);
int n;
Array.Copy(path, 0, p, 0, path.Length);
while (p[0] != x)
{
n = p[0];
Array.Copy(p, 1, p, 0, p.Length - 1);
p[p.Length - 1] = n;
}
return p;
}
static bool isNew(int[] path)
{
bool ret = true;
foreach (int[] p in cycles)
if (equals(p, path))
{
ret = false;
break;
}
return ret;
}
static int smallest(int[] path)
{
int min = path[0];
foreach (int p in path)
if (p < min)
min = p;
return min;
}
static bool visited(int n, int[] path)
{
bool ret = false;
foreach (int p in path)
if (p == n)
{
ret = true;
break;
}
return ret;
}
}