# Google Interview Experience for Girl Hackathon 2023

Last Updated : 03 Aug, 2023

In Google Girl Hackathon 2023, We will solve 2 Questions with Detailed Solutions:
Question 1: Have you ever encountered a string with balanced brackets and wondered how many additional characters you need to insert to satisfy a specific condition?

In this hackathon, we solved this problem for you.

• Given a string S consisting of opening and closing brackets, we will find the minimum number of additional characters needed to be inserted in S to ensure that each pair of matched brackets contains at least one ‘+’ character within it.
• We are providing a detailed solution with code examples in Java, C++, and Python, explaining the intuition, approach, time complexity, and space complexity of the solution.
• For example, if you have the string “()(())”, the output will be 2, indicating that two ‘+’ characters need to be inserted to satisfy the condition.

Are you ready for another challenge?

In this hackathon, we had tackle the problem of maximizing equal numbers in an array.

Given an array a of n elements and an integer k, we will perform a specific operation on each element to obtain the maximum length of a subsequence in which all numbers are equal.

We are providing a solution with detailed explanations and code examples in Java and C++, including the intuition, approach, time complexity, and space complexity of the solution.

For example, given the array [1, 5, 3, 1] and k = 3, the output will be 4, indicating that the maximum length of a subsequence with equal numbers is 4.
Now, Let’s have a look at that questions and it’s detailed Answers head. it is just based on my own approach.
Please! share if you have any Optimised ways to tackle this problem. I will be glad to hear from you.

Question 1:

You are given a string S of length N. It consists of only two characters:

• (: Opening bracket
• ): Closing bracket

S is a balanced bracket sequence. Formally, a sequence of brackets is balanced if the

following conditions are met:

It contains no unmatched brackets.

â€¢ The subset of brackets enclosed within the confines of a matched pair

of brackets is also a matched pair of brackets.

You are required to insert the character ‘+’ in S such that there exists at least one ‘+’ enclosed within each pair of matched bracket sequence. Find the minimum number of ‘+’ characters to be inserted in S to satisfy the provided condition.

`# Example 1:Input : ()(())Output: 2#Example 2:Input: ()((()()))Output: 3Constraints:1<=T<=101<=N<=10^5N is even.`

Solution:

1. Intuition:

`We use a stack to keep track of opening parentheses. When a closing parenthesis is encountered, it checks for a matching opening parenthesis in the stack, indicating a valid parentheses pair. By counting the number of valid pairs, the function determines the number of valid parentheses expressions in the given string.`

2. Approach:

`1. We are creating a function that takes two parameters :An Integre N,A string S.The function aims to determine the number of valid parentheses expressions in the givenstring.2. Create an empty stack named st to store opening parentheses.3. Initialize ans and flag variables to 0. ans will hold the final count of valid parenthesis expressions, and flag will be used as a flag to identify the first opening parenthesis encountered.4. Iterate through each character in the string S using a loop.5. If the current character is an opening parenthesis (i.e., '('), push it onto the stack st.Additionally, if flag is 0 (indicating the first opening parenthesis encountered), increment ansby 1 and set flag to 1.6. If the current character is a closing parenthesis (i.e., ')'), set flag back to 0 and pop an opening parenthesis from the stack st. This indicates a valid parentheses pair.7. After iterating through all the characters in S, the function returns the final value of ans, which represents the count of valid parentheses expressions.3. Time Complexity: O(N)The time complexity of the provided code is O(N), where N is the length of the string S. The code iterates through each character in S once.4. Space Complexity: O(N)The space complexity is also O(N), as the stack st can potentially hold all the opening parentheses in the worst case scenario.`

## C++

 `class` `Solution{` `public``:` `       ``int` `ValidParenthesis(``int` `N, string S){` `             ``stack<``char``> st; ``//to store opening parenthesis.` `             ``int` `ans = 0; ``//hold final count of valid parenthesis` `             ``int` `flag = 0; ``//identify the fisrt opening parentheis encountered.` `         ``for` `(``int` `i = 0; i < N; i++){` `           ``//if current char is a opening parenthesis` `          ``if` `(S[i] == ``'('``) {` `             ``st.push(S[i]); ``//push it onto the stack` `           ``//if flag is 0 set it to 1 and increment ans.` `          ``if` `(flag == 0){` `                     ``ans++;` `                     ``flag = 1;` `                    ``}` `            ``}` `          ``//else set flag back to 0 and pop opening parenthesis from stack.` `           ``else``{` `                ``flag = 0;` `                ``st.pop();` `         ``}` `    ``}` `           ``return` `ans;` `//TC: O(N)` `//SC: O(N)` `      ``}` `};`

## Java

 `/*package whatever //do not write package name here */`   `import` `java.io.*;` `import` `java.util.Stack;`   `class` `Solution` `{` `public` `int` `ValidParenthesis(``int` `N, String S){`   `Stack st = ``new` `Stack<>(); ``// to store opening parenthesis.` `     ``int` `ans = ``0``; ``// hold the final count of valid parenthesis` `     ``int` `flag = ``0``; ``// identify the first opening parenthesis encountered` `     ``for` `(``int` `i = ``0``; i < N; i++){` `// if the current char is an opening parenthesis` `     ``if` `(S.charAt(i) == ``'('``) {` `           ``st.push(S.charAt(i)); ``// push it onto the stack` `     ``// if flag is 0, set it to 1 and increment ans` `     ``if` `(flag == ``0``){` `          ``ans++;` `          ``flag = ``1``;` `                   ``} ` `           ``}` `        ``// else set the flag back to 0 and pop the opening parenthesis from the stack` `       ``else``{` `             ``flag = ``0``;` `             ``st.pop();` `            ``}` `        ``}` `          ``return` `ans;` `             ``// TC: O(N)` `            ``// SC: O(N)` `         ``} ` `      ``}`

## Python3

 `class` `Solution :` `  ``def` `ValidParenthesis(``self``, N, S):` `    ``st ``=` `[] ``# to store opening parenthesis` `    ``ans ``=` `0` `# hold the final count of valid parenthesis` `    ``flag ``=` `0` `# identify the first opening parenthesis encountered` `    ``for` `i ``in` `range``(N):` `    ``#if the current char is an opening parenthesis` `        ``if` `S[i] ``=``=` `'('``:` `           ``st.append(S[i]) ``# push it onto the stack` `      ``#if flag is 0, set it to 1 and increment ans` `        ``if` `flag ``=``=` `0``:` `           ``ans ``+``=` `1` `            ``flag ``=` `1` `       ``#else set the flag back to 0 and pop the opening parenthesis from the stack` `        ``else``:` `           ``flag ``=` `0` `          ``st.pop()` `    ``return` `ans` `# TC: O(N)` `# SC: O(N)`

Question 2: Maximize equal numbers

`You are given the following:â€¢ An array a consisting of n elementsâ€¢ Integer kFor each (1â‰¤iâ‰¤n), perform the following operation exactly one time:Replace a; by a; +x, where x Ð„ [-k, k] which denotes x should lie in the range of -k and k, both inclusive.Determine the maximum length of the subsequence of array a, such that all numbers in that subsequence are equal after applying the given operation.Notes:A subsequence of array a is an array that can be derived from array a by removing some elements from it. (maybe none or all of them)Assuming 1 based indexing.#Example:1Input: a = [1, 5, 3, 1], k = 3Output: 4#Example:2Input: a = [3, 3, 3, 5], k = 1Output: 4#Example:3Input: a = [2, 5 ,1 , 2], k = 1Output: 3Constraints:* 1<=T<=5* 1<=n<=5*10^8* 0<=k<=10^9* 1<=a[i]<=10^9`

Solution:

1. Intuition:

`We will create a vector of pairs to represent the ranges, Sorting them based on the lower bounds, and counting the maximum number of overlapping intervals using a stack-like mechanism.`

2. Approach:

`1. For each test case, it reads the values of `n`, `k`, and `a`. `n` represents the number of elements in the array `a`, and `k` represents the range within which two numbers are considered equal.2. It creates a vector of `Pair` objects called `v`, where each `Pair` contains the lower and upper bounds of the range for each element in `a`. The lower bound is obtained by subtracting `k` from the element, and the upper bound is obtained by adding `k` to the element.3. It calls the `overlap` function with the `v` vector. The `overlap` function calculates the maximum number of overlapping intervals.4. Inside the `overlap` function, it initializes variables `ans` and `count` to 0 and creates an empty vector called `data`.5. It iterates through each `Pair` in the input vector `v` and adds two pairs to the `data` vector. One pair represents the start of the interval, denoted by the `first` value of the original pair and the character 'x'. The other pair represents the end of the interval, denoted by the `second` value of the original pair and the character 'y'.6. The `data` vector is sorted in ascending order based on the `first` value using the `PairComparator` struct.7. It then iterates through the sorted `data` vector. If the second value of a pair is 'x', it increments the `count` variable, indicating the start of an interval. If the second value is 'y', it decrements the `count` variable, indicating the end of an interval. The `ans` variable keeps track of the maximum `count` encountered.8. Finally, the `overlap` function returns the maximum `ans`, which represents the maximum number of overlapping intervals.9. The `maximumEqualNumbers` function calls the `overlap` function with the `v` vector obtained from `a` and returns the result.10. In the `main` function, it reads the number of test cases (`tc`) from the input. Then, in a loop, it reads the values of `n`, `k`, and `a` for each test case.11. It calls the `maximumEqualNumbers` function with the inputs and stores the result in the `result` variable.12. Finally, it prints the `result` for each test case.3. Time Complexity: O(N log N)1. The loop in the `overlap` function that creates the `data` vector takes O(N) time, where N is the size of the input vector `v`.2. The sorting operation using `sort` function on the `data` vector takes O(N log N) time since it compares and rearranges the elements based on the `PairComparator` struct.3. The loop in the `overlap` function that iterates through the sorted `data` vector takes O(N) time since it processes each element once.4. Overall, the dominant time complexity is O(N log N) due to the sorting operation.4. Space Complexity: O(N)1. The space required by the `Pair` struct is constant since it only contains two integers.2. The `v` vector created in the `maximumEqualNumbers` function takes O(N) space since it stores N `Pair` objects.3. The `data` vector created in the `overlap` function takes O(N) space since it contains 2N elements.4. The stack-like structure created by the `stack` object takes O(N) space as well.5. Overall, the space complexity of the code is O(N) due to the space usage of the vectors and stack.`

Therefore, the time complexity of the code is O(N log N), and

he space complexity is O(N), where N is the number of intervals or the size of the input vector.

## C++

 `#include ` `#include ` `#include ` `using` `namespace` `std;` `// Define a Pair struct to represent a pair of integers` `struct` `Pair{` `        ``int` `first;` `        ``int` `second; ` `       ``Pair(``int` `first, ``int` `second) : first(first), second(second) { }` `};`   `// Define a PairComparator struct to compare pairs based on first and second values` `struct` `PairComparator{` `                 ``bool` `operator()(``const` `Pair& p1, ``const` `Pair& p2) ``const` `{` `                    ``if` `(p1.first != p2.first)` `                         ``return` `p1.first& v){` `              ``int` `ans = 0; ``// Holds the maximum overlap count` `              ``int` `count = 0; ``// Tracks the current overlap count` `              ``vector data; ``// Stores the intervals as pairs with labels 'x' and 'y'` `           ``// Convert each interval into a pair of 'x' and 'y' labels` `          ``for` `(``int` `i = 0; i < v.size(); i++){` `            ``data.push_back(Pair(v[i].first, ``'x'``));` `            ``data.push_back(Pair(v[i].second, ``'y'``));` `         ``}` `        ``// Sort the intervals in ascending order based on the values` `           ``sort(data.begin(), data.end(), PairComparator());` `        ``// Iterate over the intervals and update the overlap count` `       ``for` `(``int` `i = 0; i < data.size(); i++){` `              ``if` `(data[i].second == ``'x'``)` `                  ``count++;` `              ``if` `(data[i].second == ``'y'``)` `                  ``count--;` `          ``ans = max(ans, count);` `        ``}` `        ``return` `ans; ``// Return the maximum overlap count` `     ``}` `      ``// Function to find the maximum equal numbers` `      `  `int` `maximumEqualNumbers(``int` `n, ``int` `k, vector<``int``>& a){` `        ``vector v; ``// Stores the intervals` `       ``// Convert each number into an interval and store it in the vector` `      ``for` `(``int` `i = 0; i < n; i++){` `           ``v.push_back(Pair(a[i] - k, a[i] + k));` `              ``}` `         ``return` `overlap(v); ``// Calculate the maximum overlap using the intervals` `}`     `int` `main(){` `    ``int` `tc; cin >> tc;` `    ``while` `(tc--) {` `         ``int` `n, k; cin >> n >> k;` `         ``vector<``int``> a(n);` `        ``// Read the numbers` `         ``for` `(``int` `i = 0; i < n; ++i){` `                   ``cin >> a[i];` `                ``}` `         ``// Calculate the maximum equal numbers and print the result` `         ``int` `result = maximumEqualNumbers(n, k, a);` `         ``cout << result << endl;` `          ``}` `    ``return` `0;` `}`

## Java

 `import` `java.util.*;` `// Define a Pair class to represent a pair of integers` `class` `Pair{` `        ``int` `first;` `        ``int` `second;` `        ``Pair(``int` `first, ``int` `second){` `                         ``this``.first = first;` `                         ``this``.second = second;` `                                      ``}` `            ``}` `                   ``// Define a PairComparator class to compare pairs based on first and  second values` `class` `PairComparator ``implements` `Comparator {` `         ``public` `int` `compare(Pair p1, Pair p2){` `                           ``if` `(p1.first != p2.first)` `                                  ``return` `Integer.compare(p1.first, p2.first);` `                          ``else` `                                  ``return` `Integer.compare(p1.second, p2.second);` `                     ``}` `                ``}` `class` `Main{`   `            ``// Function to calculate the maximum overlap` `         ``static` `int` `overlap(List v){` `         `  `                      ``int` `ans = ``0``; ``// Holds the maximum overlap count` `                      ``int` `count = ``0``; ``// Tracks the current overlap count` `          ``List data = ``new` `ArrayList<>(); ``// Stores the intervals as pairs with labels 'x' and 'y'` `             ``// Convert each interval into a pair of 'x' and 'y' labels` `          ``for` `(``int` `i = ``0``; i < v.size(); i++){` `                ``data.add(``new` `Pair(v.get(i).first, ``'x'``));` `                ``data.add(``new` `Pair(v.get(i).second, ``'y'``));` `                            ``}` `           ``// Sort the intervals in ascending order based on the values` `              ``Collections.sort(data, ``new` `PairComparator());` `          ``// Iterate over the intervals and update the overlap count` `           ``for` `(``int` `i = ``0``; i < data.size(); i++){` `                   ``if` `(data.get(i).second == ``'x'``)` `                                ``count++;` `                   ``if` `(data.get(i).second == ``'y'``)` `                                ``count--;` `                    ``ans = Math.max(ans, count);` `             ``}` `            ``return` `ans; ``// Return the maximum overlap count` `         ``}` `         ``// Function to find the maximum equal numbers` `static` `int` `maximumEqualNumbers(``int` `n, ``int` `k, List a){` `       ``List v = ``new` `ArrayList<>(); ``// Stores the intervals` `     ``// Convert each number into an interval and store it in the list` `    ``for` `(``int` `i = ``0``; i < n; i++){` `              ``v.add(``new` `Pair(a.get(i) - k, a.get(i) + k));` `         ``}` `          ``return` `overlap(v); ``// Calculate the maximum overlap using the intervals` `        ``}` `public` `static` `void` `main(String[] args){` `        ``Scanner scanner = ``new` `Scanner(System.in);` `        ``int` `tc = scanner.nextInt();` `        ``while` `(tc-- > ``0``){` `          ``int` `n = scanner.nextInt();` `          ``int` `k = scanner.nextInt();` `       ``List a = ``new` `ArrayList<>();` `       ``// Read the numbers` `       ``for` `(``int` `i = ``0``; i < n; ++i){` `              ``a.add(scanner.nextInt());` `            ``}` `         ``// Calculate the maximum equal numbers and print the result` `        ``int` `result = maximumEqualNumbers(n, k, a);` `       ``System.out.println(result);` `      ``}` `    ``scanner.close();` `     ``}` `}`

## Python3

 `class` `Pair :`   `   ``def` `__init__(``self``, first, second):` `       ``self``.first ``=` `first` `        ``self``.second ``=` `second`   `class` `PairComparator :` `   ``def` `__lt__(``self``, p1, p2):` `       ``if` `p1.first !``=` `p2.first:` `          ``return` `p1.first < p2.first` `        ``else``:` `          ``return` `p1.second < p2.second` `    ``def` `overlap(v): ` `        ``ans ``=` `0` `# Holds the maximum overlap count` `        ``count ``=` `0` `# Tracks the current overlap count` `        ``data ``=` `[] ``# Stores the intervals as pairs with labels 'x' and 'y'` `      ``# Convert each interval into a pair of 'x' and 'y' labels` `      ``for` `i ``in` `range``(``len``(v)):` `        ``data.append(Pair(v[i].first, ``'x'``))` `        ``data.append(Pair(v[i].second, ``'y'``))` `      ``# Sort the intervals in ascending order based on the values` `       ``data.sort(key ``=` `lambda` `x: (x.first, x.second))` `      ``# Iterate over the intervals and update the overlap count` `      ``for` `i ``in` `range``(``len``(data)):` `        ``if` `data[i].second ``=``=` `'x'``:` `          ``count ``+``=` `1` `        ``if` `data[i].second ``=``=` `'y'``:` `          ``count ``-``=` `1` `          ``ans ``=` `max``(ans, count)` `      ``return` `ans ``# Return the maximum overlap count`   `    ``def` `maximumEqualNumbers(n, k, a):` `       ``v ``=` `[] ``# Stores the intervals` `       ``# Convert each number into an interval and store it in the list` `       ``for` `i ``in` `range``(n):` `           ``v.append(Pair(a[i] ``-` `k, a[i] ``+` `k))` `    ``return` `overlap(v) ``# Calculate the maximum overlap using the intervals`   `     ``tc ``=` `int``(``input``())` `     ``while` `tc > ``0``:` `        ``n, k ``=` `map``(``int``, ``input``().split())` `        ``a ``=` `list``(``map``(``int``, ``input``().split()))` `      ``# Calculate the maximum equal numbers and print the result` `        ``result ``=` `maximumEqualNumbers(n, k, a)` `    ``print``(result)`   `     ``tc ``-``=` `1`

Previous
Next