Showing posts with label Google. Show all posts
Showing posts with label Google. Show all posts

Monday, May 13, 2024

[Google][CareerCup] Json parser library

Problem: JSON parsing is an essential toolkit in modern web development. Whether you are on the client side or server side, these methods need to be fast, efficient and dependable. But what if one day, suddenly, all of the JSON parser libraries went missing. You have been called upon to save us all from impending doom.

Please re-implement the standard json parsing methods in your favorite language and restore the world to it's natural order. Please note that to simplify the things key is a string and value is either a string or a json object. No other data type is allowed.

You need to write following methods:

  1. Constructor: Make an object of the class.
  2. Serialize: Returns the json string.
  3. Deserialize: Save the json string in a data structure.


Example:

Input: ["JsonParser", "Deserialize("{a:{h:hat},b:{c:{f:fish,g:goat},d:doll},e:elephant,i:{j:jar, k:kite,l:lion}}")", Serialize()]
Output: [None, None, "{a:{h:hat},b:{c:{f:fish,g:goat},d:doll},e:elephant,i:{j:jar, k:kite,l:lion}}"]


Approach: This can be done using many DS like trees, dictionary/map but I am using Linked List here with child pointer. As for me it looks like a list, where if value is another list of key value pair then we can say it is child otherwise it's simple data stored in the node.

Each comma ',' says this is next node. With this thought just look at the implementation to understand the solution in more details.

Please note that I haven't tested it throroughly so there might be some corner cases where the below program will fail but the approach will remain same.


Implementation in C#:

public class ListNode

{

    public string Key {get; set;}

    public string Value { get; set; }

    public ListNode Next {get; set;}

    public ListNode Child {get; set;}

    public ListNode(string key)

    {

        this.Key = key;

    }

}


public class JsonParser

{

    public JsonParser()

    {

        this.head = null;

    }

    

    public void Deserialize(string str)

    {

        this.Clear();

        int currIndex = 1;

        this.head = this.DeserializeToList(str, ref currIndex);

    }

    

    private ListNode DeserializeToList(string str, ref int currIndex)

    {

        // Nothing to consume

        if (currIndex >= str.Length)

        {

            return null;

        }

        int keyIndex = str.IndexOf(":", currIndex);

        // No key exist means wrong input

        if (keyIndex == -1)

        {

            return null;

        }

        // Get key

        string key = str.Substring(currIndex, keyIndex - currIndex);

        // Create the node

        ListNode node = new ListNode(key);

        // First case when value is string

        if (str[keyIndex + 1] != '{')

        {

            int bracketIndex = str.IndexOf("}", keyIndex + 1);

            int commaIndex = str.IndexOf(",", keyIndex + 1);

            int valIndex = Math.Min(bracketIndex, commaIndex);

            if (valIndex == -1)

            {

                valIndex = bracketIndex;

            }

            string val = str.Substring(keyIndex + 1, valIndex - (keyIndex + 1));

            node.Value = val;

            currIndex = valIndex + 1;

        }

        // Second case when value is JsonObject, Need to initialize child

        else

        {

            currIndex = keyIndex + 2;

            node.Child = this.DeserializeToList(str, ref currIndex);

        }

        // In case of closing bracket there is no next node.

        if (str[currIndex - 1] == '}')

        {

            node.Next = null;

            ++currIndex;

        }

        // In case of comma there is a next node.

        else

        {

            node.Next = this.DeserializeToList(str, ref currIndex);

        }

        // Current node is properly initialized now

        return node;

    }

    

    public string Serialize()

    {

        return this.SerializeToStr(this.head);

    }

    

    private string SerializeToStr(ListNode node, bool isNext = false)

    {

        if (node == null)

        {

            return "";

        }

        // In case of next we don't need to wrap around brackets

        string str = isNext ? "" : "{";

        str += node.Key + ":";

        // If value is null means child is there so serialize it first before moving

        // to next

        if (node.Value == null)

        {

            str += this.SerializeToStr(node.Child);

        }

        else

        {

            str += node.Value;

        }

        // Go to next node

        if (node.Next != null)

        {

            str += ("," + this.SerializeToStr(node.Next, true));

        }

        str += isNext ? "" : "}";

        return str;

    }

    

    public void Clear()

    {

        this.head = null;

    }

    

    private ListNode head;

}


Complexity: O(n) for both serialize and deserialize

Tuesday, March 12, 2024

[Google][LeetCode] Keys and Rooms

Problem: There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

Example:

Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation: 
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.


Approach: If we look at this problem closely, we will come to know the given array is kind of a graph where one node is connected to another node (room) if it has key to that room so we just need to DFS on this graph and check if the number of visited nodes are equal to the number of rooms. If yes, return true; false otherwise.


Implementation in C#:

    public bool CanVisitAllRooms(IList<IList<int>> rooms)
    {
        int numOfRooms = rooms?.Count ?? 0;
        if (numOfRooms <= 1)
        {
            return true;
        }
        HashSet<int> visitedRooms = new HashSet<int>();
        this.CanVisitAllRoomsDFS(rooms, 0, visitedRooms);
        return visitedRooms.Count == numOfRooms;
    }

    private void CanVisitAllRoomsDFS(IList<IList<int>> rooms,
                                     int currRoom,
                                     HashSet<int> visitedRooms)
    {
        if (visitedRooms.Contains(currRoom))
        {
            return;
        }
        visitedRooms.Add(currRoom);
        IList<int> neighbourRooms = rooms[currRoom];
        foreach (int room in neighbourRooms)
        {
            this.CanVisitAllRoomsDFS(rooms, room, visitedRooms);
        }
    }

Complexity: O(n)

Friday, December 30, 2022

[Google][GeeksForGeeks] Longest substring with k unique characters

Problem: Given a string you need to return longest possible substring that has exactly K unique characters. If there is more than one substring of longest possible length, then print any one of them. If there are no such substring, return empty string.

Example:

Input: str = "aabbcc", k = 2
Output: "aabb"
Explanation: Can return "bbcc"


Approach: This is a straight forward sliding window problem. We can use a map to maintain the characters and their count in the current window. Whenever the number of keys in the map are equal to the k, we can check if current window length is more than max length then we can update the max length.

if length of current window is more than k then we need to slide the window from the left. That's all!


Implementation in C#:

    private static string MaxSubstringWithKUniqueChars(string str, int k)

    {

        int length = str?.Length ?? 0;

        if (length < k)

        {

            return "";

        }     

        Dictionary<char, int> freqMap = new Dictionary<char, int>(); 

        int start = 0, maxLength = 0, startIndex = -1;

        for (int end = 0; end < length; ++end)

        {

            if (!freqMap.ContainsKey(str[end]))

            {

                freqMap[str[end]] = 0;

            }

            ++freqMap[str[end]];

            if (freqMap.Count == k)

            {

                int currLength = end - start + 1;

                if (maxLength < currLength)

                {

                    maxLength = currLength;

                    startIndex = start;

                }

            }

            while (freqMap.Count > k)

            {

                --freqMap[str[start]];

                if (freqMap[str[start]] == 0)

                {

                    freqMap.Remove(str[start]);

                }

                ++start;

            }

        }

        return startIndex != -1 ? str.Substring(startIndex, maxLength) : "";

    }


Complexity: O(n)

Sunday, December 11, 2022

[Google][LintCode] Next Closest Time

Problem: Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

You may assume the given input string is always valid. For example, "01:34", "12:09" are valid. "1:34", "12:9" are invalid.

Example:

Input: "19:34"
Output: "19:39"
Explanation:
The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.  
It is not 19:33, because this occurs 23 hours and 59 minutes later.
Input: "23:59"
Output: "22:22"
Explanation:
It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.


Approach: Let's try to find out the next digit for each position in "HH:MM" from right to left. If the next digit is greater than current digit, return directly and keep other digits unchanged.

Here is the steps: (Let's take an example say "17:38")

  • Retrieve all four digits from given string and sort them in asscending order,"17:38"->digits[] {'1', '3', '7', '8'}
  • Call findNext() from the right most digit to left most digit, which actually try to find next greater digit from digits[](if exist) which is suitable for current position, otherwise return the minimum digit (digits[0]):
  • "HH:M#": There is no upperLimit for this position (0-9). Just pick the next different digit in the sequence. In the example above,'8' is already the greatest one, so we change it into the smallest one (digits[0]i.e.'1') and move to next step. ("17:38" -> "17:31")
  • "HH:#M": The upperLimit is '5' obviously (max 59 seconds). The next different digit for '3' is '7', which is greater than '5', so we can't take it, hence we take the smallest one digits[0]. ("17:31" -> "17:11")
  • "H#:MM": the upperLimit depends on previous digit which is time[0]. If time[0] is '2', then upper limit is '3' (20 - 23) else no upperLimit (0-9). Here we have time[0] as '1', so we can choose any digit we want. The next digit for '7' is '8', so we change it and return the result directly. ("17:11" -> "18:11")
  • "#H:MM": the upperLimit is'2' (00 - 23).


Implementation in C#:

        public string NextClosestTime(string time)
{
char[] result = time.ToCharArray();
char[] digits = new char[] {
                                time[0],
                                time[1],
                                time[3],
                                time[4] };
Array.Sort(digits);
result[4] = this.findSuitableDigit(
                            digits,
                            '9',
                            result[4]);
if (result[4] > time[4])
{
return new string(result);
}
result[3] = this.findSuitableDigit(
                            digits,
                            '5',
                            result[3]);
if (result[3] > time[3])
{
return new string(result);
}
result[1] = this.findSuitableDigit(
digits,
result[0] == '2' ? '3' : '9',
result[1]);
if (result[1] > time[1])
{
return new string(result);
}
result[0] = this.findSuitableDigit(
                            digits,
                            '2',
                            result[0]);
return new string(result);
}

private char findSuitableDigit(
char[] digits,
int upperLimit,
char currDigit)
{
if (currDigit == upperLimit)
{
return digits[0];
}
int i = 0;
while (i < digits.Length &&
                digits[i] <= currDigit)
{
++i;
}

if (i == digits.Length)
{
return digits[0];
}

return digits[i] > upperLimit ?
                digits[0] :
                digits[i];
}

Complexity: O(n) (The length is constant)

Friday, December 2, 2022

[Google][LintCode] Longest Substring with At Most K Distinct Characters

Problem: Given a string S, find the length of the longest substring T that contains at most k distinct characters.

Example:

Input: S = "eceba", k = 2
Output: 3 ("ece")
Input: S = "aa", k = 1
Output: 2 ("aa")


Approach: We will use Sliding Window approach here. We will increase the window till the number of unique characters in window is less than k. Obviously we will use a map here to keep track of it. We will also keep tracking of the max length by comparing the maxLength variable to the current window length.


Implementation in C#:

    public int LengthOfLongestSubstringKDistinct(string s, int k)

    {

        int start = 0, end = 0, maxLength = 0;

        Dictionary<char, int> charFreqMap = new Dictionary<char, int>();

        while (end < s.Length)

        {

            if (!charFreqMap.ContainsKey(s[end]))

            {

                charFreqMap[s[end]] = 0;

            }

            ++charFreqMap[s[end]];

            while (charFreqMap.Keys.Count > k)

            {

                --charFreqMap[s[start]];

                if (charFreqMap[s[start]] == 0)

                {

                    charFreqMap.Remove(s[start]);

                }

                ++start;

            }

            maxLength = Math.Max(maxLength, end - start + 1);

            ++end;

        }

        return maxLength;

    }


Complexity: O(n)

[Google][LeetCode] Palindrome Permutation II

Problem: Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

Example:

Input: "aabb"
Output: ["abba", "baab"]
Input: "abc"
Output: []


Approach: We are using hashmap to store the frequency of each character of the given string. We know that if there are more than one character exist with odd frequency than there will be no palindrome permutation of the given string. 

If we find a character with odd frequency then we also know that it has to be in the middle of any palindrome permutation. With this understanding we will generate all the palindromic permutation of the string s with the help of the hashmap.


Implementation in C#:

    public static List<string> GeneratePalindromes(string s)

    {

        int length = s?.Length ?? 0;

        List<string> result = new List<string>();

        if (length == 0)

        {

            return result;

        }        

        int[] charFreqMap = new int[26];

        foreach (char ch in s)

        {

            ++charFreqMap[ch - 'a'];

        }        

        bool isOddFreqCharFound = false;

        int oddIndex = -1;

        for (int i = 0; i < 26; ++i)

        {

            if (charFreqMap[i] % 2 == 1)

            {

                if (isOddFreqCharFound)

                {

                    return result;

                }

                isOddFreqCharFound = true;

                oddIndex = i;

            }

        }

        string currResult = "";  

        if (isOddFreqCharFound)

        {

            currResult += ((char)(oddIndex + 'a')).ToString();

            --charFreqMap[oddIndex];

        }

        GetPalindromePermutation(charFreqMap, currResult, result, length);

        return result;

    }

    

    private static void GetPalindromePermutation(int[] charFreqMap, string currResult, List<string> result, int maxLength)

    {

        if (currResult.Length == maxLength)

        {

            result.Add(currResult);

            return;

        }        

        for (int i = 0; i < charFreqMap.Length; ++i)

        {

            if (charFreqMap[i] > 0)

            {

                charFreqMap[i] -= 2;

                char ch = (char)(i + 'a');

                GetPalindromePermutation(charFreqMap, ch + currResult + ch, result, maxLength);

                charFreqMap[i] += 2;

            }

        }

    }


Complexity: ??

Saturday, June 25, 2022

[Google][LintCode] Add Bold Tag in String

Problem: Given a string s and a list of strings dict, you need to add a closed pair of bold tag and to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them.

Example:

Input: s = "abcxyz123", target = ["abc", "123"]
Output: "<b>abc</b>xyz<b>123</b>
Input: s = "aaabbcc", target = ["abc", "123"]
Output: "<b>aaabbc</b>c


Approach: Here we will take a marking boolean array which will tell us whether the current character should be mark bold or not. You can look at the implementation to understand the solution which very much straight forward.


Implementation in C#:

        public static string AddBoldTag(string s, string[] dict) 

{

            int length = s?.Length ?? 0;

            if (length == 0)

            {

                return null;

            }

            bool[] bold = new bool[length];

            int currEnd = 0;

            for (int i = 0; i < length; ++i)

            {

                foreach(string word in dict)

                {

                    if (StartsWith(s, i, word))

                    {

                        currEnd = Math.Max(currEnd, i + word.Length);

                    }

                }

                bold[i] = i < currEnd;

            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; ++i)

            {

                if (bold[i] && (i == 0 || !bold[i - 1]))

                {

                    sb.Append("<b>");

                }

                sb.Append(s[i]);

                if (bold[i] && (i == length - 1 || !bold[i + 1]))

                {

                    sb.Append("</b>");

                }

            }

            return sb.ToString();

        }

private static bool StartsWith(string s, int index, string word)

        {

            for (int i = 0; i < word.Length; ++i)

            {

                if (index + i >= s.Length)

                {

                    return false;

                }

                if (s[index + i] != word[i])

                {

                    return false;

                }

            }

            return true;

        }


Complexity: O(n * w * lw) where n is the length of s, w is the number of strings in dict and lw is the length of the largest string in dict.

Thursday, September 23, 2021

[Google] Minimize Max Distance to Gas Station

Problem: On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = stations.length.

Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized.

Return the smallest possible value of D.

Example:

Input: stations = [1,2,3,4,5,6,7,8,9,10], K = 9
Output: 0.5
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.

Constraints:

  • stations.length will be an integer in range [10, 2000].
  • stations[i] will be an integer in range [0, 10^8].
  • K will be an integer in range [1, 10^6].
  • Answers within 10^-6 of the true value will be accepted as correct.


Approach: We are going to use binary search here. How? What is our sorted array here, it is given as input that is our stations distance array. What is initial left? left is the lowest distance possible which is 0. Now  what is initial right; The right will be the maximum distance possible in the given array which is last station distance - first station distance. 

Now we will take the mid of left and right distance and see how many stations can be placed if we use mid distance. If number of station can be placed is <= k then we know that we can make the distance less so we will make right = mid and otherwise if the stations placed are more than k then we have to make distance more i.e. we need to make left = mid.

In the end we can return left or right.

 

Implementation in Java:

    public double minmaxGasDist(int[] stations, int k) {

        int length = stations.length;

        double left = 0;

        double right = stations[length - 1] - stations[0];

        while (right - left > 1e-6) {

            double mid = left + (right - left) / 2;

            if (isFeasible(stations, k, mid)) {

                right = mid;

            }

            else {

                left = mid;

            }

        }

        return right;

    }


    private boolean isFeasible(int[] stations, int k, double dist) {

        int count = 0;

        for (int i = 1; i < stations.length; ++i) {

            count += (int)((stations[i] - stations[i - 1]) / dist);

        }

        return count <= k;

    }


Complexity: O(nlogD) where D is the difference between station[n-1] and stations[0].

Thursday, September 9, 2021

[Google Question][LeetCode] Sum of Distances in Tree

Problem: There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

Example:

Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.

Input: n = 1, edges = []
Output: [0]

Input: n = 2, edges = [[1,0]]
Output: [1,1]


Approach: We can apply BFS taking every node as root and we can get our answer but this will be expensive solution as it will take O(n^2) time. Let's try to optimize it.

Let's say our tree is:

        0

      /.   \

    1.       2

  /         /    \ 

5.        3      4

Now let's say we calculated the distance for 0 which will be 8. Now let's try to calculate the distance of 1 -

     1

  /.      \

5.          0 [distance is 8]

                \

                   2

                 /.    \

               3        4

Here we already know that the sum of distances from 0 to every every node is 8. We can divide the this value into two part:

  1. distances of 0 to 1 and its children 
  2. distances of 0 to 2 and its children

Now when we calculate the same distances 1, we can say the sum of distances from 1 is going to be:

distances[0] - Number of Nodes in subtree with root as 1 + Number of nodes in subtree with root as 2 + 1 (for 0) = 

distance[0] - Number of Nodes in subtree with root as 1 + TotalNodes in tree - Number of Nodes in subtree with root as 1

Why? If you see for each node in the subtree(1), we are reducing the distance by 1 because instead of parent of 1 that is 0, we are now starting from 1. Similarly for each node in the subtree(2), we are adding 1 in the distance because instead of starting from 0, we are starting from the other 1, something like:

1 - 0.- 2 <

so the distance we need to add is the distance between 1 - 0 that is 1 to reach 2 and its children as there is no other way to reach subtree(2) from 1. If it is understood than we can have the generic formula:

distance[node] = distance[parentOfNode] - NumOfChildren[node] + (NumNodes - NumOfChildren[node])

We can use post order traversal to calculate the number of nodes in each subtree and initial distance calculation then we can use pre order traversal to calculate the final distances. Have a look at the implementation for more details.

That's all!


Implementation in C#:

public class Graph

{

    public int[] SumOfDistancesInTree(int n, int[][] edges) 

    {

        if (n == 1)

        {

            return new int[n];    

        }

        this.InitializeMembers(n);

        this.CreateGraph(edges);

        this.GetChildrenCountAndInitialResult(0, -1);   

        this.GetDistances(0, -1);

        return this.dist;

    }

    

    private void GetDistances(int node, int parent)

    {

        foreach (int child in this.graph[node])

        {

            // Bidirectional graph instead of visit set we can use this condition here.

            if (child == parent)

            {

                continue;

            }

            dist[child] = dist[node] - this.numOfChildren[child] + (this.numOfNodes - this.numOfChildren[child]);         

            this.GetDistances(child, node);

        }

    }

    

    private void GetChildrenCountAndInitialResult(int node, int parent)

    {

        foreach (int child in this.graph[node])

        {

            // Bidirectional

            if (child == parent)

            {

                continue;

            }

            this.GetChildrenCountAndInitialResult(child, node);

            this.numOfChildren[node] += this.numOfChildren[child];

            this.dist[node] += (this.dist[child] + this.numOfChildren[child]);

        }

        ++this.numOfChildren[node];

    }

    

    private void CreateGraph(int[][] edges)

    {

        foreach (int[] edge in edges)

        {

            this.graph[edge[0]].Add(edge[1]);

            this.graph[edge[1]].Add(edge[0]);

        }

    }

    

    private void InitializeMembers(int n)

    {

        this.numOfNodes = n;

        this.numOfChildren = new int[n];

        this.dist = new int[n];

        this.graph = new HashSet<int>[n];

        for (int i = 0; i < n; ++i)

        {

            this.graph[i] = new HashSet<int>();

        }

    }

    

    private HashSet<int>[] graph;

    private int[] numOfChildren;

    private int[] dist;

    private int numOfNodes;

}


Complexity: O(n)

Tuesday, August 31, 2021

[Google Question][LeetCode] Making A Large Island

Problem: You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

Return the size of the largest island in grid after applying this operation.

An island is a 4-directionally connected group of 1s.

Example:

Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.


Approach: If you see it is kind of (not exactly) connected components problem in Graph. We can solve it in 2 steps:

  1. We can first apply DFS from every cell which is not visited and has value 1. We will make this current cell parent for every reachable cell with value 1 using a map / 2D array. We also record the size of this component and we can store in a map with mapping like {parent_cell => component_size}.
  2. We again parse the grid and whenever we see a cell with 0. We can calculate it's neighbours component size and sum them. We add 1 into this sum as we are going to make this cell 1. This is what the island size we can get by changing this cell from 0 to 1. We can just take the maximum of all such islands' sizes and that will be our answer. 


Implementation in C#:

    public int LargestIsland(int[][] grid) 

    {

        int rows = grid?.Length ?? 0;

        if (rows == 0)

        {

            return 0;

        }

        int cols = grid[0].Length;

        // To store component size

        int[,] componentSizeMap = new int[rows, cols];

        // To store component's parent

        KeyValuePair<int?, int?>[,] componentParentMap = new KeyValuePair<int?, int?>[rows, cols];

        for (int i = 0; i < rows; ++i)

        {

            for (int j = 0; j < cols; ++j)

            {

                KeyValuePair<int?, int?> currCell = new KeyValuePair<int?, int?>(i, j);

                if (grid[i][j] == 1 && 

                    componentParentMap[i,j].Equals(default(KeyValuePair<int?, int?>)))

                {

                    int componentSize = 0;

                    this.MakeComponentUsingDFS(

                        grid, 

                        componentParentMap, 

                        currCell, 

                        i, 

                        j, 

                        ref componentSize);          

                    componentSizeMap[i, j] = componentSize;

                }

            }

        }        

        int maxSize = 0;

        bool hasZero = false;

        for (int i = 0; i < rows; ++i)

        {

            for (int j = 0; j < cols; ++j)

            {

                if (grid[i][j] == 0)

                {

                    hasZero = true;

                    maxSize = Math.Max(

                        this.GetNeighborComponetSizesSum(

                            grid, 

                            i, 

                            j, 

                            componentParentMap, 

                            componentSizeMap) + 1, 

                        maxSize);

                }

            }

        }

        return hasZero ? maxSize : rows * cols;

    }

    

    private int GetNeighborComponetSizesSum(

        int[][] grid, 

        int row, 

        int col, 

        KeyValuePair<int?, int?>[,] componentParentMap, 

        int[,] componentSizeMap)

    {

        // Taking hashset as multiple neighbours can have same parent.

        HashSet<KeyValuePair<int?, int?>> parentsSet = new HashSet<KeyValuePair<int?, int?>>();

        //Left Neighbor

        if (this.IsValidCell(grid, row - 1, col))

        {

            parentsSet.Add(componentParentMap[row - 1, col]);

        }

        //Right Neighbor

        if (this.IsValidCell(grid, row + 1, col))

        {

            parentsSet.Add(componentParentMap[row + 1, col]);

        }

        

        //Top Neighbor

        if (this.IsValidCell(grid, row, col - 1))

        {

            parentsSet.Add(componentParentMap[row, col - 1]);

        }

        //down Neighbor

        if (this.IsValidCell(grid, row, col + 1))

        {

            parentsSet.Add(componentParentMap[row, col + 1]);

        }

        int neighborSize = 0;

        foreach (var parent in parentsSet)

        {

            neighborSize += componentSizeMap[parent.Key.Value, parent.Value.Value];

        }

        return neighborSize;

    }

    

    private void MakeComponentUsingDFS(

        int[][] grid, 

        KeyValuePair<int?, int?>[,] componentParentMap, 

        KeyValuePair<int?, int?> parent, 

        int currRow, 

        int currCol, 

        ref int componentSize)

    {

        if (!componentParentMap[currRow, currCol].Equals(default(KeyValuePair<int?, int?>)))

        {

            return;

        }

        componentParentMap[currRow, currCol] = parent;

        ++componentSize;

        // Left Neighbor

        if (this.IsValidCell(grid, currRow -  1, currCol))

        {

            this.MakeComponentUsingDFS(

                grid, 

                componentParentMap, 

                parent, 

                currRow -  1, 

                currCol, 

                ref componentSize);

        }

        // Right Neighbor

        if (this.IsValidCell(grid, currRow +  1, currCol))

        {

            this.MakeComponentUsingDFS(

                grid, 

                componentParentMap, 

                parent, 

                currRow +  1, 

                currCol, 

                ref componentSize);

        }

        // Top Neighbor

        if (this.IsValidCell(grid, currRow, currCol - 1))

        {

            this.MakeComponentUsingDFS(

                grid, 

                componentParentMap, 

                parent, 

                currRow, 

                currCol - 1, 

                ref componentSize);

        }        

        // Down Neighbor

        if (this.IsValidCell(grid, currRow, currCol + 1))

        {

            this.MakeComponentUsingDFS(

                grid, 

                componentParentMap, 

                parent, 

                currRow, 

                currCol + 1, 

                ref componentSize);

        }

    }

    

    private bool IsValidCell(int[][] grid, int row, int col)

    {

        return row >= 0

            && row < grid.Length

            && col >= 0

            && col < grid[0].Length

            && grid[row][col] == 1;

    }


Complexity: O(n^2)

Monday, August 23, 2021

[Google Question] Given a binary tree with string stored leaf node and number of characters in left subtree stored in other nodes, get the substring given index and length.

Problem: You are given a binary tree in which every leaf node has a string and other nodes have the number of characters in their left subtree.  

Given an index and length, return the substring from the binary tree. 

Example:

Chart

Description automatically generated

Input: Tree: above tree, index = 2, length = 10
Output: As pointed in the image "cdefghijkl"
Explanation: If you see the string is "abcdefghilmno", Its substring (2, 10) is "cdefghijkl".


Approach: We can use preorder traversal here. We need to first find the character at given index. Once we find that character, after that we don't need index (we can make it 0) as we just need "length" number of characters.  

Look at the implementation to understand the approach in detail.


Implementation in C#:

      public static string GetString(BinaryTreeStringNode root, int index, int len) 

        { 

            if (root == null) 

            { 

                return string.Empty; 

            } 

            return GetStringInternal(root, ref index, len); 

        } 


        private static string GetStringInternal(BinaryTreeStringNode node, ref int index, int len) 

        { 

            if (node == null) 

            { 

                return string.Empty; 

            } 

            // Got the leaf node, get the substring 

            if (node.Left == null && node.Right == null) 

            { 

                string result = node.Value.Substring(index, len); 

                // Get the starting point, now make index 0 as we just need 'len' number of chars 

                index = 0; 

                return result; 

            } 

            int leftCharsLength = int.Parse(node.Value); 

            // No need to go to left subtree 

            if (leftCharsLength <= index) 

            { 

                index = index - leftCharsLength; 

                return GetStringInternal(node.Right, ref index, len); 

            } 

            // No need to go to right subtree 

            if (leftCharsLength >= index + len) 

            { 

                return GetStringInternal(node.Left, ref index, len); 

            } 

            int numCharsFoundInLeftTree = leftCharsLength - index; 

            return GetStringInternal(node.Left, ref index, numCharsFoundInLeftTree) + GetStringInternal(node.Right, ref index, len - numCharsFoundInLeftTree); 

        }


Complexity: O(n) assuming string operation will take constant time.