Similar Problems

Similar Problems not available

Zuma Game - Leetcode Solution

Companies:

LeetCode:  Zuma Game Leetcode Solution

Difficulty: Hard

Topics: breadth-first-search string stack dynamic-programming  

Problem Statement:

You are given a string s and an integer k. You can remove at most k adjacent characters from s at once.

Return the final string after all such removals have been made.

If at any point there are less than k adjacent characters remaining in s you should stop.

Example:

Input: s = "abbccc", k = 2 Output: "acc" Explanation: Remove "bb" to get "acccc". Remove "cc" to get "ac".

Solution:

Approach:

The given problem can be solved using a stack data structure. We can use a stack to remove adjacent characters in the string s. If we find k adjacent characters, we remove them from the stack. We repeat this process until there are less than k adjacent characters remaining in s. At each step, we need to check if the top k characters in the stack are the same. If they are, we remove them from the stack.

Algorithm:

  1. Initialize an empty stack as S.
  2. For each character c in the string s: a. If the stack S is empty, push the character c onto the stack. b. Otherwise, if the top k characters of the stack S are the same as c, remove the top k characters from the stack S. c. Otherwise, push the character c onto the stack S.
  3. Create an empty string as result.
  4. While the stack S is not empty, remove the top character c from the stack S and append it to the string result.
  5. Return the string result.

Code:

class Solution { public: string removeDuplicates(string s, int k) { stack<pair<char, int>> st; for (int i = 0; i < s.size(); i++) { if (st.empty() || st.top().first != s[i]) { st.push(make_pair(s[i], 1)); } else { st.top().second++; if (st.top().second == k) { st.pop(); } } } string result = ""; while (!st.empty()) { pair<char, int> p = st.top(); st.pop(); for (int i = 0; i < p.second; i++) { result += p.first; } } reverse(result.begin(), result.end()); return result; } };

Time Complexity:

The time complexity of this algorithm is O(n) where n is the length of the input string s.

Space Complexity:

The space complexity of this algorithm is O(n) where n is the length of the input string s.

Zuma Game Solution Code

1