Meeting Rooms

Given an array of intervals representing N meetings, find out if a person can attend all the meetings.

Input:
[[6,7],[2,4],[8,12]]
Output:
true
Explanation:
None of the meetings overlap with each other.

Input:
[[1,4],[2,5],[7,9]]
Output:
false
Explanation:
Meetings [1,4] and [2,5] overlap with each other.
This problem is commonly asked nowadays in Amazon, Facebook and Microsoft interview.


Thought Process

A person can not attend two or more meetings at one time. It means if the timings of two meetings are overlapping, then she/he will not able to attend it.
Now, the question comes in your mind that How to recognize/check that the two meetings are overlapping or not. We will use the time interval to check that the meetings are overlapping or not.

Follow below picture to get to know about overlapping.

Meeting Rooms
These are are the 4 Overlapping Situations.

Now, we have to check if one meeting interval is overlapping with other, then it is impossible to attend that meeting.

Brute Force

The Simple Solution is to compare every two meetings using the nested for loop and to check whether the intervals are overlapping or not. Two meetings overlap if one meeting is going on and other meeting starts before finishing the first meeting.

class Solution {
public:
    bool check_overlap(vector<int>first, vector<int>second)
    {
        if((first[0]>=second[0] && first[0]<second[1]) 
           || (second[0]>=first[0] && second[0] <first[1])){
            return true;
        }
        return false;
    }
    bool canAttendMeetings(vector<vector<int>>& intervals) {
        int i,j;
        
        for(i=0;i<intervals.size();i++)
        {
            for(j=i+1;j<intervals.size();j++)
            {
                if(check_overlap(intervals[i],intervals[j]))
                {
                    return false;
                }
            }
        }
        return true;
    }
};

Time Complexity of the brute force implementation is O(n2), due to nested for loop where as space complexity is O(1)

Using Merge Intervals Technique

In this, what we do is we merge all the overlapping intervals. After Merging, we compare the number of intervals before merging and after merging. If the number of intervals is the same, then there are no conflicts in the meetings, it will run smoothly(no overlapping situation). If the total number of intervals are less after merging, then it means there were some overlapping intervals, so there will be conflicts in meetings.

If you wan to learn merging intervals in detail, go here.

First, Sort the intervals in ascending order.
  1. Initiate a 2-D vector array.
  2. Add the first interval into it.
  3. for every other intervals
    • check if the last interval in the vector array is overlapping with current interval, then pop the last interval from vector array and merge the both intervals and push it in the vector array.
    • check if the last interval in he vector array is not overlapping with current interval, push current interval in the vector array.
  4. if(size of vector array formed < size of initial intervals array given)
    • return false
    • else return true;
class Solution {
public:
    bool canAttendMeetings(vector<vector<int>>& intervals) {
        int i,j;
        
        vector<vector<int>>v;
        if(intervals.size()==0)
        {
            return true;
        }
        sort(intervals.begin(), intervals.end());
        vector<int>l;
        l.push_back(intervals[0][0]);
        l.push_back(intervals[0][1]);
        v.push_back(l);
        
        for(i=1;i<intervals.size();i++)
        {
            vector<int> prev=v.back();
            //time to merge
            if(intervals[i][0]<prev[1])
            {
                l.clear();
                v.pop_back();
                l.push_back(prev[0]);
                l.push_back(max(prev[1],intervals[i][1]));
                v.push_back(l);
            }
            else
            {
                v.push_back(intervals[i]);
            }
        }
        if(intervals.size()==v.size())
        {
            return true;
        }
        return false;
        
    }
};

The time complexity is O(nlogn) and space complexity is O(n)

Sorting

what we do here is that we sort the array in ascending order. After sorting, we compare the meeting with the previous meeting and make sure that the meeting should not overlap. If it overlaps, return false otherwise return true.

class Solution {
    static bool compare(vector<int>v1, vector<int>v2) {
        return v1[0] == v2[0] ? v1[1] > v2[1] : v1[0] < v2[0];
    }
public:
    bool canAttendMeetings(vector<vector<int>>& intervals) {
        
        sort(intervals.begin(), intervals.end(), compare);
        
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i-1][1] > intervals[i][0])
                return false;
        }
        
        return true;
    }
};

The time Complexity is O(nlogn) and space complexity is O(1)

Please write to us if something is missing or wrong, we will be happy to fix it.

This article is contributed by Monika Bhasin

Maximal square area

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area. This problem is known as maximal square area problem. For example,


Input: 
1 0 1 0 0 
1 0 1 1 1 
1 1 1 1 1
1 0 0 1 0 

Output:
4

Thought process

What is the basic condition for a square? Basic condition for a square is that its length and breadth should be equal. For any cell to be included into the square, it has to be stretch from three sides: length wise, breadth wise and diagonally. So, to know if a cell will increase the size of the square? maximum square area We can recursively find the longest side of the square at each cell i,j. Keep track of the global maximum while getting the side at each cell.

Show me the implementation

class Solution {
    int max = 0;
    public int maximalSquare(char[][] matrix) {
        
        int rows = matrix.length;
        
        if(rows == 0) return 0;
        
        int cols = matrix[0].length;
        
        for (int i = rows-1; i >=0; i--)
		for (int j = cols-1; j>=0; j--)
			max = Math.max(max, maxSquareUtil(matrix, i, j));

        return max * max;
    }
    
    private int maxSquareUtil(char[][] matrix, 
                      int i, int j){
        
        if(i == 0 || j == 0){
            return matrix[i][j] -'0';
        }
        
        int c = (matrix[i][j] == '1' ) ? Math.min(
            maxSquareUtil(matrix, i-1, j),
            Math.min(maxSquareUtil(matrix, i, j-1), 
                  maxSquareUtil(matrix, i-1, j-1))
        ) + 1 : 0;
        
        return c;
        
    }
}
It is quite obvious from the solution that the optimal solution of a subproblem leads to the optimal solution of the original problem. However, let’s look at the execution tree of the code. maximal square area Now, the two conditions necessary for applying dynamic programming are present: optimal subproblem solution leads to the optimal solution to a bigger problem and there are overlapping subproblems.

What can we do to avoid recalculating the solution from subproblems again and again? We can save solutions to problems in the cache. Whenever we want to solve the problem, we first check in the cache, if it is present, we do not solve it again and use the cache value. If not present, then we calculate it.

Top-down approach

class Solution {
    int max = 0;
    public int maximalSquare(char[][] matrix) {
        
        int rows = matrix.length;
        
        if(rows == 0) return 0;
        
        int cols = matrix[0].length;
        
        int [][] cache = new int[rows][cols];
        
	    for (int i = 0; i < rows; i++) {
		    for (int j = 0; j < cols; j++)
			    cache[i][j] = -1;
	    }
        
        for (int i = rows-1; i >=0; i--)
		    for (int j = cols-1; j>=0; j--)
			    max = Math.max(max, 
                                 maxSquareTopDown(matrix, cache,i, j));

        return max * max;
    }
    
    private int maxSquareTopDown(char[][] matrix, int[][] cache, 
                                  int i, int j){
        
        if(i == 0 || j == 0 || matrix[i][j] == '0' ){
            cache[i][j] = matrix[i][j] -'0';
            return matrix[i][j] -'0';
        }
        
        if(cache[i][j] != -1){
            return cache[i][j];
        }
        
        cache[i][j] = Math.min(
            maxSquareTopDown(matrix, cache, i, j-1),
            Math.min(maxSquareTopDown(matrix, cache, i-1, j-1), 
                maxSquareTopDown(matrix, cache, i-1, j))
        ) + 1;
        
        return cache[i][j];
        
    }
}

The time complexity of the code is O(n * m) with additional space complexity of O(n * m).

Bottom-up approach

We can think of the problem from the bottom-up view. What will be the size of a square for each cell? If the cell is 1, the size will be 1 and if the cell is 0, then it will be zero.
  • Construct an array dp[][] for the given matrix[][].
  • Copy first row and first columns as it is from matrix[][] to dp[][]
  • For other entries, use following expressions to construct dp[][]
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 if matrix[i][j] == 1 else 0
Find the maximum entry in dp[][] and return its square.

show me the bottom-up implementation

    public int maximalSquare(char[][] matrix) {
        
        int rows = matrix.length;
        
        if(rows == 0) return 0;
        
        int cols = matrix[0].length;
        
        int[][] dp = new int[rows][cols];
        for(int i = 0; i < rows; i++){
            if(matrix[i][0] == '1') {
                max = 1;
                dp[i][0] = 1;
            }
        }
        
         for(int i = 0; i < cols; i++){
            if(matrix[0][i] == '1') {
                max = 1;
                dp[0][i] = 1;
            }
        }
        
        for(int i = 1; i < rows; i++){
            for(int j = 1; j < cols; j++){
                if(matrix[i][j] == '1'){
                    dp[i][j] = Math.min(dp[i-1][j], 
                           Math.min(dp[i][j-1], dp[i-1][j-1])) + 1;
                    max = Math.max(dp[i][j], max);
                }
            }
        } 
        
        return max * max;
    }
The time complexity of the code is O(n * m) with additional space complexity of O(n * m).

Longest subarray without repeated numbers

Given an array, find the length of the longest subarray which has no repeating numbers.

Input: 
A = {1,2,3,3,4,5}
Output: 
3
Explanation: 
Longest subarray without any repeating elements are {1,2,3} & {3,4,5}.

Thought Process

1. Brute Force

In this approach, you will consider each subarray and then check whether that particular subarray contains no repeating elements or not. Right? So let’s find out how expensive this task would be? The complexity of generating subarray of an array would be O(n2), and when I will generate a particular subarray then I have to check whether the subarray contains unique elements(will use a map for this) or not, which will take O(n) time.

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

2. Sliding Window Solution

Sliding Window Technique is a method for finding subarrays in an array that satisfy given conditions. If you’re new to Sliding Window technique, visit this Sliding Window, it will be helpful for you. In Short words, I can say that maintaining a subset of items as our window, and resizing and moving that window until we find a solution.

We will use two pointers to construct our window. To expand the window, we have to increment the right pointer and to shrink the window we have to increment the left pointer.

We will increment the right pointer by 1 until the property of the subarray is not violated if the property gets violated, we have to shrink the window(means increment the left pointer by 1) till the subarray contains the repeating letters. We have to repeat this step until the value of the right pointer <= array Size.

  • Here, Property means the subarray should contain only the unique elements.

Initially, left and right pointers both are at 0th index.

  1. Add the value of arr[right] into the map.
    • After adding the value, if map[arr[right]] is 1, that is ok.
      Increment the right pointer by 1.
      Update the maxSize of the window variable.
    • After adding the value into map, if map[arr[right]] is 2, it means that our window contains repeating elements. Now, we have to shrink the window from left so that our window always contains the unique elements.
      Increment the left pointer and parallely decrement the value of the map[arr[left]]by 1.
      Do this thing until the value of the map[arr[right]]becomes 1.
  2. Repeat the 1st step, till the right < arraySize

Time Complexity – O(n), where n is the number of integers in the array.
Space Complexity – O(k), where k is the number of distinct integers in the input array. This also means k<=n, because in worst case, the whole array might not have any repeating integers so the entire array will be added to the map.

longest subarray without repeating numbers

Implementation

#include<bits/stdc++.h>;
using namespace std;
int lengthOfLongestSubarray(vector<int>v)
{
    if(v.size()==0)
    {
        return 0;
    }
    map<int,int> mapy;
    int left=0, right=0;
    int max_window=-1;

    for(right=0;right<v.size();right++)
    {
        int num=v[right];
        mapy[num]=mapy[num]+1;
        
        while(left < right && mapy[num] > 1){
           mapy[v[left]]=mapy[v[left]]-1;
           left=left+1;
        }
        //calculating max_length of window
        max_window=max(max_window,right-left+1);
    }
    return max_window;
}
main()
{
    vector<int>v={1,2,3,3,4,5};
    cout<<lengthOfLongestSubarray(v);
}

This post is contributed by Monika Bhasin.

Single number in an array

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Example 1:
Input: [2,2,1,3,4,3,5,4,5,]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4

Approach 1

You will be thinking it’s a very simple problem. What we all need to do is to take count of each distinct number and that number having count 1 will be our answer. We can achieve it by using a dictionary.

Time Complexity – 0(N)
Space Complexity – 0(N)

What if your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? It means you have to solve the problem in O(N) time complexity and constant space that means space complexity must be O(1).

Think of an approach before going into the post.

Let me tell you, have you ever heard of Bit Manipulation?

‘’ As the name suggests, it is a process of performing logical operations on bits to achieve the desired result.’’

To understand the bit manipulation let’s first have a look at Logical Bitwise Operators.

  1. AND (&)
  2. OR ( | )
  3. XOR (^)
  4. Left Shift (<<)
  5. Right Shift (>>)

In our particular problem, we will implement Bitwise XOR to get the desired result.

Properties of Bitwise XOR (^)–

  1. 0 ^ 0 = 0
  2. 0 ^ 1 = 1
  3. 1 ^ 0 = 1
  4. 1 ^ 1 = 0

If we observe the above operations we find that XOR of the same bits results in 0 and XOR of two different bit results into 1.

Now, Let’s have a look on some other examples –

  • 1 ^ 1 ^ 1 ^ 1 = 0
  • 2 ^ 2 = 0
  • 1 ^ 1 ^ 2 = 2
  • 2 ^ 3 ^ 4 ^ 3 ^ 2 = 4 (XOR operation is commutative and associative)

Now pause and observe the above examples very carefully.

Approach 2

So, If you observe carefully you will find that XOR of all those numbers appearing twice are being cancelled out and we are left with the number that appears only once. It clearly means if there are N numbers out of which N-1 numbers appears twice (or even number of times) and one number appear only once, then XOR of all numbers collectively results into that number which appears only once (See Examples 6, 7, 8) and as a result we will get our desired number.

As in example 8, 2 appears twice (so 2 ^ 2 = 0) and 3 appears twice (3 ^ 3 = 0) and 4 appears only once so as a consequence we will get 4 (0 ^ 0 ^ 4 = 4)

So in order to solve our particular problem we need to find XOR of all the numbers of array and and resultant XOR will be our answer.

Python Solution –

def singleNumber(Arr, n):
        ans=0
        for i in range(N):
            ans^=Arr[i]
        return ans

Steps-

  1. Iterate over all elements of array
  2. Find the XOR of all elements of array and store it into a variable ans.
  3. Return ans.

Complexities –

  1. Time Complexity – O(n)
  2. Space Complexity- O(1)

This article is contributed by Md Taslim Ansari

Subarrays with given sum

We are given an unsorted array containing positive and negative numbers, we need to find the number of subarrays with the given sum, k. For example,

Input: 
arr = [2, 4, -5, -5, 6] and k = -10
Output: 
1
Explanation: 
We can see that there is only one subarray (index 2 to 3) whose sum is -10. 

Thought process

If the sum of elements in the range [0, i] and [0, j] is the same, then we can say that the sum between [i + 1, j] will be zero. This statement will be more clear after understanding the below example.

Let’s take arr = [2, 4, 4, -10, 4, 6, 5, 6]. Sum of elements in the range [0, 2] = 2 + 4 + 4 = 10
Sum of elements in the range [0, 5] = 2 + 4 + 4 + (-10) + 4 + 6 = 10

The above two sums are the same. Here,i= 2 and j = 5. Let’s check whether the sum in the range [3, 5] is 0 or not. Sum of elements in the range [3, 5] = -10 + 4 + 6 = 0

Hence, the statement explained above is true.

Read more here: subarray with sum zero

We can extend this idea to this question. The modified statement is as follows if the difference of the sum of elements in the range [0, j]and [0, i] is k, then we can say that the sum between [i + 1, j] is k. Mathematically,

If Sum[0, j] - Sum[0, i] = k, where j > i
Then, Sum[i + 1, j] = k or Sum[0, j] - k = Sum[0, i]

For each index j in the array, if we have seen Sum[0, j] – k in the past, then we have found the subarray. But how to achieve this?

Let’s number of elements in an array is n. So, we need to maintain sum[0, 0], sum[0, 1], sum[0,2], sum[0, 3] … sum[0, n].
These sums are known as prefix sum. If the same sum occurs many times, we store the frequency of occurrence. We can use a hashmap where the key will denote the sum and value will denote the frequency of occurrence.

Any corner cases? What if k = sum[0, j], where j is an index. For this, sum[0, j] – k is 0 and we will try to find if we have seen 0 as the sum in the past. To handle this case, we will insert one entry to map as a map[0] = 1.

Algorithm

1. For each index in the array.
      1.1 sum = sum in the range [0, i]
      1.2 Check if sum - k is already encountered in the array, 
      i.e have we encountered any array in the past whose 
      the sum is sum - k. 
      1.3 If yes, add the frequency of sum - k to answer.
2. Finally, put the sum in the map with frequency as 1 if the sum is not seen in the past. 
3. If the sum is seen in the past, update frequency as old frequency + 1.
4. Finally, print the answer.

Show me the implementation

// nums = given array
// k = sum
int subarraySum(vector<int>& nums, int k) {
    	int ans = 0;   // to store the final count
        int sum = 0;  // to store sum
   	
        // to store prefix sum along with frequency
    	map<int, int> map;  
    	map[0] = 1;  // for case like k = sum[0, i]
   	  
    	for(int i = 0; i < nums.size(); i++)
    	{
                // calculating sum in the range[0, i]
        	sum += nums[i];    
                 // if sum - k is alread seen 
        	if(map.find(sum - k) != map.end())            
            	    ans += map[sum - k]; // add frequency
       	 
                // if sum is not seen in the past
        	if(map.find(sum) == map.end())    
            	    map[sum] = 1;
        	else 
            	    map[sum] = map[sum] + 1;
    	}
   	 
    	return and;
}

Time Complexity of the implementation is O(n) along with the space Complexity of O(n).

This article is contributed by Mukul Vashishtha

Find friend groups

There are Nstudents in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if Ais a direct friend of B, and Bis a direct friend of C, then Ais an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students. For example,

Input: 
[[1,1,0,0,0,0],
 [1,1,0,0,0,0],
 [0,0,1,1,0,0],
 [0,0,1,1,1,0],
 [0,0,0,1,1,0],
 [0,0,0,0,0,1]
]
Output: 3

Thought process

When we talk about the connections or relationships, we immediately will think of graph data structure. The node is the person and the edge is the relationship between two persons. So, first, we have to figure out whether it will be a directed graph or an undirected graph. In this problem, the friendship is a mutual relationship, thus the graph is undirected.

When you are reading this problem, the concept of Strongly Connected Components(SCC) will come into your mind. Ok, we will discuss why? If A is a friend of B, B is a friend of C, then A will be a friend of C. What does it mean? A is indirectly connected to C. It means that every friend can reach every other friend through a path if they are directly or indirectly connected. So in this way, they are forming a strong group or circle, in which every vertex is connected directly or indirectly in its group/circle. Notice that all friends (both direct and indirect), who should be in one friend circle are also in one connected component​ in the graph. 

A particular group of friends is a single component. In this problem we are going to find out how many components are there in the graph.

friend groups

When you make a graph out of it. It will be like this(see below fig). It means there are 3 friends circles.

friend-circle

We can solve this problem using 2 methods: depth first search and disjoint set method

Using Depth first traversal method

Finding connected components for an undirected graph is very easy. We can do either BFS or DFS starting from every unvisited vertex, and we get all strongly connected components

1. Initialize all nodes as not visited.
2. Initialize variable count as 1.
3. for every vertex 'v'.
       (i) If 'v' is unvisited
            Call DFS(v)
            count=count+1
DFS(v)
1. Mark 'v' as visited.
2. Do following for every unvisited neighbor `u`
      recursively call DFS(u)

DFS based approach implementation

class Solution {
Public:
    void DFS(int node,vector<vector<int>> edges,vecto<bool>visited)
    {
        int i;
        visited[node]=true;
        for(int i=0;i<edges[node].size();i++)
        {
            if(edges[node][i]==1 && node!=i && visited[i]==false)
            {
                DFS(i,edges,visited);
            }
        }
    }

    //Main Method
    int findCircleNum(vector<vector<int>> edges) {
        int i,j;
        
        int n=edges.size();
        int count=0;
        vector<bool>visited(m);
        
        //mark all the nodes as unvisited
        for(i=0;i<n;i++)
        {
            visited[i]=false;
        }
        
        for(i=0;i<n;i++)
        {
            if(visited[i]==false)
            {
                DFS(i,edges,visited);
                count=count+1;
            }
        }
        
        return count;
    }
};

Complexity

  • Time Complexity: Since we just go along the edges and visit every node, it will be O(n).
  • Space Complexity: O(n), to store the visited nodes.

Using Disjoint Sets(Union Find)

So, how to think that this problem is solved by Disjoint Sets(union-find algorithm)?

 The answer is simple because we need to keep track of the set of elements(here friends) partitioned into a number of non-overlapping subsets. Disjoint Sets(Union Find) always do this work very efficiently. We will use the Union by Rank algorithm to solve this problem.

If you haven’t heard of the Disjoint Sets. Go to this link and read about it.

To join two nodes, we will compare the rank of parents of both nodes.

  • If the rank is equal, we can make any one of the parent’s node as a parent and increment the rank of the parent node by 1.
  • If the rank is not same, then we can make the parent whose rank is greater than other.

graph breadth first traversal application

 

Let’s start solving this.

Union(1,2): 1 is a parent of itself and 2 is parent of itself. As both of them have different parents, so we have to connect them, and we will any of the parent as root, in this case we chose 1 and make it a parent.

friend groups

Union(2,1): 1 is a parent of itself and 1 is a parent of 2, as both of them have the same parents, already joined.

Union(3,4) :3 is a parent of itself and 4 is a parent of itself. Both of them have different parents, we need to join them.

Union(4,3): 3 is parent of itself and 3 is the parent of 4. Both of them have the same parents, already joined.

Union(4,5):   3 is the parent node of 4 and 5 is the parent node of 5. Since parents are different, we have to compare the rank of the parents of both 4 and 5 nodes. 3 has higher rank then 5, it will be parent of 5 .(Used Path Compression) as shown in the below fig.

Union(5,4): As now, 4 and 5 have the same parents, already joined. Last is the node 6 which connected to itself. So, nothing to do there. At the end of this exercise, we found that there are three different sets in the graph, and that is our answer of number of groups of friends in this graph or matrix.

Disjoint set based approach implementation

class Solution {
public:
    class Node
    {
        public:
            int data;
            Node*parent;
            int rank=0;
    };
    //make a set with only one element.
    void make(int data)
    {
        Node*node=new Node();
        node->data=data;
        node->parent=node;
        node->rank=0;
        mapy[data]=node;
        return;
    }
    map<int,Node*> mapy;
    //To return the address of the particular node having data as `data` 
    Node*find(int data)
    {
        auto k=mapy.find(data);
        if(k==mapy.end())
        {
            //There is no any node created, create the node
            make(data);
            return mapy[data];
        }
        else
        {
            return mapy[data];
        }
        return NULL;
    }
    /*Find the representative(parent) recursively and does path compression  
    as well*/
    Node*parents(Node*node)
    {
        if(node->parent==node)
        {
            return node;
        }
        return node->parent = parents(node->parent);
    }
    //Main Method
    int findCircleNum(vector<vector<int>>edges) {
        int i,j;
        
        vector<int> v;
        int m=edges.size();
        int n=edges[0].size();
        for(i=0;i<m;i++)
        {
            for(j=0;j<n;j++)
            {
                if(edges[i][j]==1)
                {
                    int a=i;
                    int b=j;
                    
                    
                    Node*A=find(a);
                    Node*B=find(b);
            
                    Node*PA=parents(A);
                    Node*PB=parents(B);
            
                    if(PA==PB)
                    {
                    }
                    else
                    {
                        if(PA->rank>=PB->rank)
                        {
                            //increment rank if both sets have Same rank
                            PA->rank=(PA->rank==PB->rank)?PA->rank+1:PA->rank;
                            PB->parent=PA;
                        }
                        else
                        {
                            PA->parent=PB;
                        }
                    }
                    
                    }
                }
            }
        
        int number=0;
        for(auto k: mapy)
        {
            if(k.second->parent==k.second)
            {
                number=number+1;
            }
        }
        return number;
    }
};

Complexity

  • Time Complexity: For each of the edge, we need to find the parents  and do the union, which is O(mlogn).
  • Space Complexity: We used a map to store the parent information, O(n).

This post is contributed by Monika Bhasin

Longest Mountain in Array

The mountain at index i in array arris defined such that

arr[i-N]..arr[i-1]< arr[i] > arr[i+1] arr[i+N] 

where i cannot be 0 and arr.length-1 which means that the index(i) cannot be at the extreme ends in the array (start and end of an array). Given an array A of integers, return the length of the longest mountain.  Return 0 if there is no mountain. Minimum length of a mountain subarray should 3.

Example 1:

Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Thought process

Question is to find the mountain which has longest length which means the length of the increasing array ending at arr[i] + the length of the decreasing array starting at arr[i] should be longest among all the mountains in an array, then we can return that length as longest mountain length.

Also if there is a flattening curve as in case of [2,3,3] there is no peak, the flat curve will not be a part of a mountain. The answer for [2,3,3] is 0. Here are couple of inputs and expected answers. This is a good clarifying question in an interview.

Idea is that for each index i, we will keep a track of how many numbers are there towards the left of the indexiare in increasing order and how many numbers on the right side of the index i, which are in decreasing order. If the length of the mountain with index i has its peak is longer than earlier seen mountains, we update the longest length.

It is important to note that both side subarray should be monotonically increasing and decreasing. As soon as we hit a flat curve (consecutive duplicates numbers), the duplicate elements can not part of the mountain array .

Also note that we jump the left to the next number to the mountain array, because no index in this mountain array will make a bigger mountain than the current one. See why?

show me the solution

 public int longestMountain(int[] arr) {
        
        if(arr==null || arr.length<3) return 0;
        
        int left=1;
        int len=arr.length-1;
        int ans=0;
        
       while(left<=len){
           
           int upHill=0;
           int downHill=0;
           
           // if there are duplicates on the left ,
           //they wont be the part of the mountain
           while(left<=len && arr[left]==arr[left-1]) left++;
           
           while(left<=len && arr[left]>arr[left-1]) {
               upHill++;
               left++;
           }
           
           while(left<=len && arr[left]<arr[left-1]) {
               downHill++;
               left++;
           }
           
           // if the sequence is 2, 3, 3, 5 , then the 
           // downHill will not be greter than 0 at left = 2
           if(upHill>0 && downHill>0) {
               ans=Math.max(ans,upHill+downHill+1);
           }
           
       }
        return ans;
    }

The time complexity of the implementation is O(n)

.

Trapping rain water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after rain. For example,

Input: [0,1,0,2,1,0,1,3,2,1,2,1] 
Output: 6

trapping rain water

Basic thought

We know water stays at the highest level it is able to, and it always maintains the same flat surface. Using this, we can infer that we need to find holes in the elevation where water would be able to rest at a level. To calculate how much water these holes would need to store, we can see that we need to have elevations on both sides, and we also need to track how much space a particular hole would be able to trap the water. Fig below is an example of a hole which holds 4 units of water.

trap water

Upon further breakdown of these holes, we can notice that we do not need to track the entire hole to find the capacity it holds, but we can parse each unit of the hole individually. Thus, the amount of water in each unit of the hole is

min(leftHeight, rightHeight) - currentUnitHeight.

What remains now is to calculate the leftHeight and the rightHeight. We could parse through them individually to find these out, but we can see a general pattern here: The highest elevation to the left inclusive of the current unit will become the leftHeight, and the highest elevation to the right inclusive of the current unit will become the rightHeight. The problem has been greatly simplified into maintaining track of highest heights on both sides of every unit.

Brute force solution

From our observations in the previous section, the simplest brute force approach is to calculate the highest elevation on both sides of every unit, and sum them up together. Each unit takes O(n) time with this approach, and there are n units to calculate in total. Thus, this approach will take O(n2) time.

Show me the brute force implementation

class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) < 3:
            return 0
        ans = 0
        for i in range(len(height)):
            left_max = 0
            right_max = 0
            for j in range(i + 1):
                left_max = max(left_max, height[j])
            for j in range(i, len(height)):
                right_max = max(right_max, height[j])
            ans += min(left_max, right_max) - height[i]
        return ans

Dynamic Programming approach

As we can see from the brute force solution, we calculate the leftHeight and the rightHeight multiple times for the same node, i.e. the problem has overlapping subproblems. Thus a dynamic programming approach should optimize the brute force approach further. We can store the leftHeight and rightHeight elements till each index we have iterated, and thus the water storage calculation for each unit will now take O(1) time. Overall, this approach passes over the array thrice, and thus has a runtime of O(n) with a space complexity of O(n).

Show me the dynamic programming implementation

class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) < 3:
            return 0
        ans = 0
        left_max = [0] * len(height)
        right_max = [0] * len(height)
        left_max[0] = height[0]
        right_max[-1] = height[-1]
        for i in range(1, len(height)):
            left_max[i] = max(height[i], left_max[i - 1])
        for i in reversed(range(len(height) - 1)):
            right_max[i] = max(height[i], right_max[i + 1])
        for i in range(1, len(height) - 1):
            ans += min(left_max[i], right_max[i]) - height[i]
        return ans

Stacks

Since we need to keep track of the highest elevations up to a point, stacks are a good approach to perform this operation in one pass of the array. The basic idea is since we need to store the largest elevations in the stack, as we iterate through the array, we can find the amount of water stored till the currentHeight is higher than elements of the stack and move on to the next value, i.e. water stored will always be of a hole shape, thus we can find the amount of water that can be stored between two high values. This operation passes over the array once, and each element can only have two operations maximum: Pushing and popping from the stack, thus its time complexity is O(n). The space complexity will be O(n), in case the entire array is stored on the stack.

Show me the stack implementation

class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) < 3: return 0 ans = 0 stack = [] for i in range(len(height)): while len(stack) > 0 and height[i] > height[stack[-1]]:
                top = stack.pop()
                if len(stack) == 0:
                    break
                # Distance between the larger value still in the 
                #stack with a hole the height of the top element 
                #and the current element
                distance = i - stack[-1] - 1
                # Water that can be stored is smaller 
                # heights between these bounds, and the height 
                # of the intermediate region between top of the stack 
                # and current index
                curr_height = min(height[i], height[stack[-1]]) - height[top]
                ans += distance * curr_height
            stack.append(i)
        return ans

Simple Optimization

Another way to approach the problem is that since we need to find the maximum elevations on either side to calculate the current water stored, we can calculate the global maximum in one pass, and once we have the index for the same, we can iterate to it and from it to the rest of the array knowing that we have one bounded measurement which is the highest elevation in the array. The time complexity for this operation is O(n), but there are two passes over the array(once to calculate global maximum, and once to calculate the water amount). The space complexity is O(1).

Show me the implementation

class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) < 3:
            return 0
        ans = 0
        gMax = 0 # Global Max
        for i in range(len(height)):
            gMax = i if height[gMax] < height[i] else gMax
        lMax = 0 # Left max yet
        for i in range(1, gMax):
            lMax = i if height[lMax] <= height[i] else lMax
            ans += max(0, height[lMax] - height[i])
        lMax = len(height) - 1 # Right max yet
        for i in reversed(range(gMax, len(height) - 1)):
            lMax = i if height[lMax] <= height[i] else lMax
            ans += max(0, height[lMax] - height[i])
        return ans

This article is contributed by Khushman Patel

Russian doll envelopes

There are a number of envelopes with widths and heights given as a pair of integers (w, h). An envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. Given the list of such envelope dimensions, find the maximum number of envelopes can you Russian doll? (put one inside other) For example:

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3 
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

How should we go about the solution? One of the ways is to find all the subsets of the envelopes and check every subset if envelopes can fit in each other. This solution has exponential time complexity. Can we do better than that?

Let’s look at the conditions again, an envelope can fit in another one only if width and height are smaller than the other envelope. Let’s simplify this. An envelope cannot fit into another one if the width is bigger than the other. What if we sort the envelopes based on their width? Then we are sure that i-th envelop can have all the envelopes inside it that are at index 0 to i-1 as far as the height permits.

Once, we order the envelopes based on width, our problem reduces to one dimension, which is height. Now if we want to find how many will fit in each other till envelope i, we find the envelopes from 0 to i-1 in increasing order. Why? Because even if the height of the envelope j is greater than height of envelope k, where k > j, it will not fit because width of envelope j is less than width of envelope k because of the sorted order.

To find the maximum number, all we have to is to find the longest increasing subsequence based on the height of envelopes.

One thing which you should take care of is what if the width of the two envelopes is the same? In that case, those two will not fit in together in each other even if heights are increasing. To handle this case, if widths are equal, we will put the envelope with a bigger height in front of the other, so that both envelopes are not part of increasing subsequence.

Show me the implementation

class Solution {
    public int maxEnvelopes(int[][] envelopes) {
        
        if(envelopes == null || envelopes.length == 0) return 0;
      
        /*Sort the array based on width in increasing order,
           if the width is equal, sort it based on height
           in decreasing order.
        */
        Arrays.sort(envelopes, (a,b) -> a[0] == b[0] 
                           ? b[1] - a[1] : a[0] - b[0]);
        
        int n = envelopes.length;
        
        int [] dp = new int[n];
        int len = 0;
        
        for(int[] envelope : envelopes){
            int index = Arrays.binarySearch(dp, 0, len, envelope[1]);
  
            if(index < 0)
                index = -(index + 1);
            dp[index] = envelope[1];
            if(index == len)
                len++;
        }
        
        return len;
    }
}

The time complexity of implementation is O(nlogn); we are doing n times binary search on maximum n numbers and space complexity is O(n).

You can solve another problem with the same approach: Box stacking problem, where one box can be put on another one only if the area of the base is less than the area of the base of another.

Longest subarray with sum at most k

Given an array of integers A[], find the length of the longest subarray with the sum at most k where k is an integer. For example:

Input:
A[] = [10, 5, 2, 7, 1, 9], 
k = 15
Output:
4
Explanation
longest subarray with sum at most K is [ 5, 2, 7, 1 ].

Input:
A[] = {-5, 8, -14, 2, 4, 12},
k = 5
Output:
5

Longest subarray with a sum k

First of all, if you are not aware of the fundamentals of a sliding window, I would strongly recommend reading: Sliding window concept

The question is how do we know that this is a sliding window problem? Two hints are present in the problem itself, first, we are looking for a subarray i.e. a window, and second, that window has a certain property i.e with a sum of elements at most k.

We will follow the standard pattern for the sliding window; define two pointers, left(l)and right(r). l shrinks the window whenever a property of the window is violated and r expands the window. Every time we expand the window, we add the number to the current sum. If the sum becomes greater than k, we note down the length of this window and update the maximum length if this greater than the previous length. Then we start shrinking the window and subtract the numbers from the sum until the sum is less or equal to k again.

Let’s take an example and see how it works.
Longest subarray with sum at most k

Show me the implementation

package AlgorithmsAndMe;

public class SubarrayWithSumK {
    public int lengthOfSubarray(int[] a, int k){
        int l = 0;
        int r = 0;

        int len = a.length;
        int max = 0;
        int currentSum = 0;

        while(r < len){
            currentSum += a[r];

            while(l < r && currentSum > k){
                max = Math.max(max, r -l);
                currentSum -= a[l];
                l++;
            }
            r++;
        }

        return max;
    }
}

The time complexity of the above code is linear i.e O(n) with O(1) space complexity.

If you are interested, there is another similar problem on Leetcode called Subarray Product Less Than K, you can try there.

Error loading source code.

Show me the answer

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
       
        int l = 0;
        int r = 0;

        if(k == 0) return 0;
        int len = nums.length;
        int count = 0;
        int currentProd = 1;

        while(r < len){
            currentProd *= nums[r];

            while(l <= r && currentProd >= k){
                currentProd /= nums[l];
                l++;
            }
            count += r - l + 1;
            r++;
        }
        
        return count;
    }
}

Interview coming up? Check out our full coding interview prep course. There’s a get-the-job-or-your-money-back guarantee, so it only costs money if it actually works.

As always, shoot me an email if there’s anything I can help with.