7 Feb 2020

Task Scheduler

Problem Statement : 
      Given an input arrays of Tasks
          Input: tasks = [A, A, A, B, B, C,  C,  D]

and a window of size k = 3 (say)

You have schedule tasks in each CPU cycle.(1 task per CPU cycle or CPU cycle can go idle we well). Idle cycle is represented by "X".
You have to make sure no task gets repeated before k intervals, you ma have to have 'idle'  CPU cycle as well in order to achieve this. Find the minimum number of CPU cycles.

for above input

output : A  B  C  D  A  B  C  X  A  X  X  X  A

above output is one possible answer for the given input, if you observe "A" repeats atleast after k=3, for that matter any task repeats at-least after 3 CPU cycles.

Leetcode :
621. Task Scheduler
https://leetcode.com/problems/task-scheduler/

Solution :

This is a very interesting problem, and has been asked in top notch companies.
There are multiple solutions we will be the best approach to solve this. (you can solve this by sorting and using Priority queue as well).

Lets fit the above input into the grid to understand better.




The formula at the end of the above image is crucial, spend time understanding that, thats the crux of the problem.

There is a another interesting case at step 4 in the code below, it occurs when number of idle product of maxCount and k is less compared to total distinct tasks. (i recommend to pay attention to this line carefully). One example of such scenario is  ['A' , 'A' , 'B' , 'C' , 'D' , 'E', 'F' ] and k = 2 , by the above formula, your result would be  (2 - 1 ) * (2 + 1) + 1 = 4 but the correct answer is 7.



Below is the implementation of the above problem.



Please post comments and suggestions.
Happy Coding !! :)

Sliding Window Maxima

Problem Statement : 
        Given an array of size n and window of size k (k < n) , find the maximum element in each contagious array of size k(also can be called as window) .

Leetcode:
239. Sliding Window Maximum
https://leetcode.com/problems/sliding-window-maximum/


Solution : 

There are multiple approaches to solve this problem, we will be solving the problem with the help of deque(double ended queue). The brute force approach would take O(n * k) time complexity as for each n , you will have to traverse next k elements.

Below is the implementation with the help of Deque, important thing to note here is that
i. all elements which are getting out of the window range needs to be removed and
ii. if there is a new larger incoming element coming in as part of new item, remove all smaller elements in the deque.


Below is the code implementation :


Please post comments and suggestions.
Happy Coding !! :)

5 Feb 2020

Shell Sort

Problem Statement : 

Write the code for Shell Sort.

Solution : 

Shell sort is an extension of Insertion sort where number of jumps of the corrected element reduces by using simple concept comparisons of elements separated by a gap.

Below is the code for shell sort.

Thanks for visiting the page, post suggestions and comments.
Happing coding !! :)

24 Jan 2020

Distribute Coins in Binary Tree

Problem Statement : 

Distribute Coins in Binary Tree

Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.
In one move, we may choose two adjacent nodes and move one coin from one node to another.  (The move may be from parent to child, or from child to parent.)
Return the number of moves required to make every node have exactly one coin.

Solution : 

The first time I saw this question it was difficult to guess what is expected and seemed to be tough, but after discussing with my partner we came up with the solution.

The coins needs to be distributed across the tree, we at every node are returning the number coins required from left & right (which can be negative as well) and -1 (for the node itself) and passing up the tree. Whatever the requirement comes from left and right(which can be negative as well, if coins are needed) are the number of moves hence we are taking absolute value to count.
Below is the implementation.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Node {
    public Node left;
    public Node right;
    public int data;

    public Node(int data) {
        this.data =data;
    }
}
/**
 * Distribute Coins across the Tree
 */
public class DistributeCoins {

    private int result = 0;

    public int getMoves(Node root) {
        result = 0;
        distribute(root);
        return result;
    }

    private int distribute(Node root) {
        if(root == null)
            return 0;

        int left = distribute(root.left);
        int right = distribute(root.right);

        result += Math.abs(left) + Math.abs(right);
        return root.data + left + right - 1 ;
    }

    public static void main(String[] args) {
        DistributeCoins obj = new DistributeCoins();
        Node root = new Node(1);
        root.left = new Node(0);
        root.right = new Node(2);
        int moves = obj.getMoves(root);
        System.out.print("Number of Moves : " + moves);
    }
}

Thanks for visiting us.
Happy Coding !! :)

18 Jan 2020

Infix to Postfix Conversion

Problem Statement : 

Convert Infix expression to Postfix Expression.

Input :  a+b*(c^d-e)^(f+g*h)-i

Output:  abcd^e-fgh*+^*+i

Solution :

Algorithm :

1. If the character is operand, append in the Output Result.
2. If you get openings bracket '(', push into the stack.
3. If you get closing bracket ')', pop all element from the stack until you reach '(' and add in the                Output Result.
4. If the character is operator
  a. if the stack is empty, then push operator to stack.
  b. Else, Pop all the operators from the stack which have greater than or equal
  precedence than that of the current operator.
  After doing that Push the scanned operator to the stack.

Below is the implementation of the above algorithm.


Please post your comments and suggestions.
Happy Coding !! :)

Maximum Frequency Stack

Problem Statement : 

Implement FreqStack, a class which simulates the operation of a stack-like data structure.

FreqStack has two functions:

1. push(int x), which pushes an integer x onto the stack.
2. pop(), which removes and returns the most frequent element in the stack.

         If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.

Solution : 

The idea here is to maintain frequency Map and bucket of stacks. 
Below is the working code( refer the comments in the code).



Thank you for visting the page, post your comments and suggestions.
Happy Coding !! :)


14 Jan 2020

Validate Stack Sequence

Problem Statement :

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Sample 1 : 

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,

push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Sample 2 : 

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false

Explanation: 1 cannot be popped before 2.

Solution : 

Idea is to keep pushing the elements to a stack from "pushed" array and as you find same value at pushed and poped, pop the stack and move ahead in the poped array comparing stack content. 
In the end stack should be empty.


Below is the code implementation


Thank you for visting the page.

5 Jul 2019

Circular Queue

Problem Statement :
           Implement Circular Queue Using Arrays

Source Code Link
Solution:

Circular Queue is efficient version of Queue, in which elements are stored efficiently without wastage of space.
The concept that circular queue uses is incrementation of the index pointer, which is achieved by
index = (index +1 )%N , this formula brings the index to start position if it crosses the end of the array.

We will be using two pointers namely "rear" and "front".
rear pointer - tracks the latest item inserted.
front pointer - tracks the oldest item in the queue.

Below is the implementation of Circular Queue.


Now given below is implementation of all the operations present in the interface.

Any improvement or suggestions for the above code are most welcome. Source Code is hosted on Ideone , please follow the link given above.
Happy Coding!! :)

1 Jul 2019

Move all zeros to the end

Problem statement:
     Move all zeros towards the end in a given array.

Input : [0 1 2 0 3 0 0 4 0 0 0 5]

Soltion:

There are multiple approches to solve this problem, we will solve this problem using two pointers with
Space Complexity = O(1)
Time Complexity = O(n)

The idea here is to take two pointers one of which move at its speed and other one would count the number of non zero-elements.

Walk through the code for the above example.


Post your suggestions and comments.
Happy Coding !! :)


29 Jun 2019

Next Greater Element

Problem Statement:
      Print the next greater element to every element in an array , if no greater element exists for a number
 print -1.

Given Array :   7     22    4      12     25      3      9
Output:            22   25    12    25     -1      9      -1

Solution:

The above problem can be solved using stack.

Below is the sub-routine implementation:
Please comment and post suggestions
Happy Coding !! :)

28 Jun 2019

Odd one out.

Problem Statment : Find the element which occurs once where as other numbers appears N Times in an array

For example here [5, 5, 4, 8, 4, 5, 8, 9, 4, 8] all the number appear 3 times except 9 which appears 1 time.

Solution : 

This problem can be solved using bit operation in a very efficient way

Time Complexity : O(n)
Space : O(1)

Code Below :


Please post your comments and suggestions.
Happy Coding !! :)



22 Jun 2019

Rain Water Trap

Problem Statement : 
Given n non-negative integers representing building heights where the width

of each bar is 1, compute how much water it is able to trap after raining.

Below is the figure depicting the buildings and the gap between the building would trap the water.

Buildings with gaps to trap rain water.


Solution : 
   In this problem, we would calculate left max and right Max for a given bar and subtract the height of the bar from the minimum of L_max and R_max and add the result of each bar to obtain the final answer.

<math xmlns="http://www.w3.org/1998/Math/MathML"><munderover><mrow><mo>&#x2211;</mo><mo>&#xA0;</mo></mrow><mrow/><mrow><mi>n</mi><mo>-</mo><mn>1</mn></mrow></munderover></math>min(LH[i] - RH[i]) - H[i])

where LH[i] means Left Height Max ,
           RH[i] means Right Height Max and 
           H[i] means Height of building 'i'.

This is a simple gist of the problem, we will discuss the various approach to solve this problem.

Approach 1 :
  The Brute Force, this is the father of all solutions and every developer is the master of it, this is always the first answer but never accepted by the interviewer, anyways we still discuss this to optimize our solution further.

In this approach, we will traverse the elements and every element will have two pointers `left` and `right`,  left pointer will move towards left until a bigger number is found for i-th element and the right pointer will move towards right until the bigger element is found for the i-th element.

so water stored at i-th element = Min(L_max , R_max) - height[i].

I hope you will be able to code for this,  if not you can find the code here.

Time Complexity: O(n^2)
Space Complexity: O(1)

Approach 2 : 
   The Dynamic Programming(DP) approach, in this approach we will use two most important properties of DP, a. Overlapping subproblem and Optimal Substructure.

On every bar, the water collected is calculated by itself as well as a portion of it is also calculated by other bars, this is a depiction of Overlapping subproblem.

Optimal Substructure, we can represent the calculation of water on a bar that is subproblem and it is contributed by other bars as well this can be represented by the below equation.

<math xmlns="http://www.w3.org/1998/Math/MathML"><munderover><mrow><mo>&#x2211;</mo><mo>&#xA0;</mo></mrow><mrow/><mrow><mi>n</mi><mo>-</mo><mn>1</mn></mrow></munderover></math>min(LH[i] - RH[i]) - H[i])

So here we will take two arrays left[] and right[] which will store the left_max and right_max for every bar respectively at the corresponding index of the bar. Thereafter we calculate the water level stored on each bar by Min(Lmax - Rmax) - bar_height. Summation of the previous value would give us the trapped water.

Code below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     //Dynamic Programming Apporach to Trap rain water problem solution
     static int trapWaterUsingDP(int[] bars) {
     if(bars == null || bars.length < 3) 
      return 0;
     
     int len = bars.length, trappedWater = 0;
     int[] left = new int[len];
     int[] right = new int[len];
     
     //NB. for left most bar lmax would be 0, so counter is stated with 1,
     for(int i=1;i<len;i++) 
      left[i] = Math.max(left[i-1], bars[i-1]);
     
     // similarly for right most bar rmax would be 0 at len-1. 
     for(int i= len -2 ;i >= 0;i--) 
      right[i] = Math.max(right[i+1], bars[i+1]);
     
     
     for(int i=0;i<len;i++)
      trappedWater += Math.max(0, Math.min(left[i], right[i]) - bars[i]);
     
     return trappedWater;
    }

Time Complexity : O(n)
Space Complexity : O(n) , since we have used n + n which is 2n, removings constants gives us O(n) complexity

Approach 3:
   The Stack-based approach, we will now solve the above problem with the stack-based approach, in the last approach, we improved on Time Complexity but deteriorated Space complexity compared to approach 1.

This approach will give us both improved Time and Space complexity.
Algorithm below :
1. Iterate over each tower
     a. while stack is not empy and stack.peek() > current
         i. top = stack.pop()
         ii. dist = current - stack.peek() -1
         iii height = min(current, stack.peek()) - height[top]
         iv. water  += dist * height
  b. push
  c. next tower

Code below.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     //Stack based Approach to Trap rain water problem solution
     static int trapWaterUsingStack(int[] bars) {
      if(bars == null || bars.length < 3) 
       return 0;
      
      Stack<Integer> stack = new Stack<>();
      stack.push(0);
      
      int len = bars.length, waterTrapped = 0;
      for(int i=1; i < len ; i++)
      {
       while(!stack.isEmpty() && bars[stack.peek()] < bars[i]) {
        int top = stack.pop();
        if(!stack.isEmpty()) {
         int dist = stack.isEmpty() ?  0 : i - stack.peek() - 1 ;
         int effectiveHeight = Math.min(bars[i], bars[stack.peek()]) - bars[top];
            waterTrapped += dist * effectiveHeight;
        }
       }
       stack.push(i);
      }
      return waterTrapped;
     }

Time Complexity: O(n)
Space Complexity: O(n)

Approach 4: 
     Two Pointer Approach : 

In this approach,  we will use two-pointers and switch between left and right pointer for the movement.
Extreme bars will not store any water.
We will continue to move from left until left is smaller than right, as soon as right becomes smaller than left we will start move from right.



For complete code use this link (Code)
Please post your suggestions and comments.
Happy Coding !!

20 Jun 2019

Stock Span Problem

Problem Statment : 
       We are given list price of a stock for N days,  find the stock span of each day. Stock spam is defined as the consecutive number of days where the stock price was less or equal to the given day stock price.

For ex. for   P  = {11, 9, 7, 5, 4, 6, 8, 10, 7, 9}  the span is S = {1, 1, 1, 1, 1, 3, 4, 7, 1, 2}




Solution :


I hope the solution looks evident by looking at the graph, so we plot the span values of each stock price below to make it much more meaningful and clear. 



We will be discussing multiple approaches to solve the problem. 

Approach 1 : 
We will first consider the naive solution which will have a time complexity of O(n^2). 

Here for each item traverse on the left of the array until you find the element bigger than the current one. For every move towards the left increment the counter of the current element by 1.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  int[] solve1(int[] stocks) {
 int len = stocks.length, i , j ;
 int[] span = new int[len];
 span[0] = 1;
  
 for (i = 1; i < len; i++) { 
  for (j = i - 1, span[i] = 1; j >= 0 && stocks[i] >= stocks[j]; j--, span[i]++);
 }
 return span;
  }

Time Complexity: O(n^2)
Space Complexity: O(n)

We surely can do better than this, moving to the next approach


Approach 2 :

In this approach, we will consider a stack-based solution to improve Time complexity.
Here the idea is if the next element is smaller then the stock span of that element is 1 (eg,  70, 65) otherwise if the next element is greater than the top element (eg, 70, 65, 80) then there is possibility that incoming element is greater than further elements in the stack so keep popping until you find a greater element index than the current element and calculate the span using span[i] = i - price[stack.peek()]  or otherwise if the stack is empty span[i] = i+1.

Let us write the code for this. (i am writing a code in order to understand the logic, you improvise it to make it shortened).


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
  int[] solve(int[] stocks)
    {
 Stack<Integer> stack = new Stack<Integer>();
 stack.push(0);
 int[] sol = new int[stocks.length];
 sol[0]=1;
  
 for(int i=1;i<stocks.length;i++)
 {
     //if incoming element is small, Pop until u find greater element index in the stack 
     for(;!stack.isEmpty() && stocks[stack.peek()] < stocks[i]; stack.pop());
  
     sol[i] = stack.isEmpty() ? i + 1: i - stack.peek();
     stack.push(i);
 }
 System.out.println(Arrays.toString(sol));
 return sol;
    }

In spite of the fact that there are nested loops in the above code, the time complexity is O(n) because we are traversing all the elements just once. In the worst case, we may have to put all the elements into the stack and then pop out all the elements (eg. 80,70, 60, 50, 40, 90) so the complexity would be O(2*n) which is of the order of O(n).

Time Complexity: O(n)
Space Complexity: O(n)

Executable Code below:

Please post your comments and suggestions.
Happy Coding !! :)

19 Jun 2019

Largest Area in a Histogram

Problem Statement : 
      Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.




In the above histogram width of each bar is 1 and heights are H = [2, 1, 5, 6, 2, 3]. 


Solution: 

By brute force algorithm, we can consider each bar every time and consider all other bars adjacent to it which are equal or greater and find the area by Height of the bar multiplied by right and left index difference plus one

Area = Bar Height * (right_index - left_index + 1)

The time complexity for this case would be (n^2) i.e. n-squared. 

We would be discussing another optimised technique which will have a complexity of O(n) using stack. 


We would essentially use same trick as we had done in the Brute force but with storage in a stack we will find a better optimised solution, The trick is to compute left and right index of the of bar such that all bars between these indices are either equal or greater than the bar in consideration. 

Traverse all the bars from left to right and push the bar to the stack if the stack is empty or if the bar is greater than the top of the stack. Once the next incoming bar is smaller than the top of the stack, anchor the index here and this would act as right_index start. Pop the bar and calculate the area as the smallest bar for this left index would be the updated top in the stack. 
i.e. A = bar_height * (right_index - 1 -  new_top_index). 

If this is slightly confusing then lets write the algorithm for it. 

Algorithm :
1. Create a empty stack. 
2. Push i , if stack is empty or H[i] is greater than stack.peek()
3. If the bar is small set anchor to i, continue to pop the indces from the stack until H[stack.peek()] is smaller H[i], for each element poped calculate the area evert time you pop element using 

A = bar_height(of the poped index) * (i - 1 - stack.peek()) 

when stack is empty, 
A = bar_height(of the poped index) * i

update Area A if the newly computed Area is greater than previous. 

4. If all the items are over and stack is still not empty repeat process 3.

Code below :



Let me know if you have any questions in the comments section or any feedback.
Happy Coding !! :)






28 Sept 2016

Trees: Prune Sum Path

Problem Statement:
      Remove the paths from root to leaf whose sum is not equal to given K.



Given Sum = 15 = K
Source Code

Solution:


Valid paths with given sum :
 1 - > 2 - > 4 - > 8
and 1 - > 3 - > 6 - > 5

Bottom - up approach is being used to prune to the tree.

Below is the implementation.

 public static boolean prunePath(Node root, int givenSum , int currSum)
 {
  if(root==null) {
   if(givenSum==currSum)
    return true;
   else  
    return false;
  }
  
  boolean leftFlag = prunePath(root.left , givenSum , currSum+root.data);
  
  boolean rightFlag = prunePath(root.right , givenSum , currSum+root.data);
  
  if(!leftFlag)
   root.left=null;
  if(!rightFlag)
   root.right=null;
  
  return (leftFlag || rightFlag ) ;
   
 }

Please post your comments and suggestions.
Happy Coding !! :)

1 Sept 2016

Post #123 : Eating Fish Problem

Problem Statement :

Below given are two arrays indicating the size of the arrays and the direction in which they are moving. A bigger fish can eat a smaller fish if they are moving in opposite direction.

Two fishes moving in same direction cannot eat each other because all the fishes are moving at a constant speed. Print the output of the fishes which survives


Fishes with distinct sizes and with their direction of movement from their current index

10
11
8
5
3
4
6
9
2
1
7
<--<---->-->--><--<--<--<--<--
 -->

Output : 


10
11
9
3
1
7
<-- <-- <-- <-- <-- -->



Explanation of output: 

Fishes with size 10 and 11 won't collide hence escapes, 
4 eats 3,  5 eats 4 , 6 eats 5 , 8 eats 6 , 9 eats 8,  then 2 and 1 survives because their behind bigger fish 9. Fish 7 survives because from its current position it will not collide with any other fish , hence the output.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Stack;

/**
 * Bigger fisehes eat smaller ones , in diff direction , 
 * No Fish Eats any other fish of same direction. 
 * Assume all fish sizes are different
 * @author prateek
 */
public class EatFishProblem {

 
 public static void main(String[] args) {
  
  int[] arr1 = {10, 11,  8,  5,  3,   4,   6,   9,    2,    1 ,   8} ;
  int[] dir1 = {-1, -1,  1,  1,  1,  -1,  -1,  -1,   -1,   -1 ,   1} ;
  solve(arr1,dir1);
 }
 
 
 static boolean solve(int[] arr,int[] dir){
  Stack<Integer> rightDir = new Stack<Integer>();
  Stack<Integer> leftDir = new Stack<Integer>();
  int i = 0;

  
  //Skip all fishes moving to left in the beggining
  while(dir[i]!=1){
   printFish(arr[i],dir[i]);
   i++;
  }
  
  int len = arr.length ;
  while(i<len){
   if(dir[i] ==1 )
    rightDir.push(arr[i]);
   else
    leftDir.push(arr[i]);
   eatFish(leftDir,rightDir);
   //if Fishes are empty in right stack, print fishes of the left stack
   //because these fishes moving to the left wont ever collide with subsequent fishes moving the right
   if(rightDir.isEmpty())
    printStackInReverse(leftDir,-1);
    
   i++;
  }

  //Print Fishes moving the right first
  printStackInReverse(rightDir,1);
  printStackInReverse(leftDir,-1);
  
  return false;
  
 }
 
  /** Print stack in reverse order */
  static void printStackInReverse(Stack<Integer> stack, Integer direction) {
  if(stack.isEmpty())
   return ;
  
  Stack<Integer> temp = new Stack<Integer>();
  while (!stack.isEmpty()) 
   temp.push(stack.pop());

  while (!temp.isEmpty()) 
   printFish(temp.pop(), direction);
 }

 /** Eats fish from the stacks , depending on size */
 static void eatFish(Stack<Integer> left, Stack<Integer> right){
  
  while(!(left.isEmpty() || right.isEmpty())){
   
   if(left.isEmpty() || right.isEmpty())
    return ;
   else if(left.peek() > right.peek())
    right.pop();
   else if(left.peek() < right.peek())
    left.pop();
   else
    return ;
  }
  
 }
 
 static void printFish(int size, int direction){
   System.out.println(direction == 1 ? size + "-->  " : "<--"+size + "   ");
 }
 
}


Post your comments and suggestions if any.
Happy Coding :)