Given a binary string str consisting of only 0’s and 1’s. The following two operations can be performed on it:
- One digit can delete another digit i.e. a 0 can delete a 1 and vice versa.
- If at any moment, the entire string consists only 0’s or 1’s, then the respective digit is printed.
The task is to print the remaining digit which will be left at the end.
Input: str = “100”
The 1st digit is 1 and it deletes the next digit 0.
The 2nd digit, i.e. 0, is deleted and now does not exists.
Now, the 3rd digit 0 deletes the 1st digit 1.
Since now only 0 is left, the output is 0.
Input: str = “10”
Approach: For this queue data structure is used. The following steps can be followed to compute the answer:
- All the digits are added to the queue.
- Two counters are maintained as an array of size 2 del which will represent the number of floating deletes present for each digit.
- The queue is traversed until there exits at least one digit of both the types.
- Then for each digit in the queue if the delete counter for this digit is not 0, then it is deleted.
- Else, the delete counter for the opposite digit is incremented and placed back into the queue.
Below is the implementation of the above approach:
Time Complexity: O(N)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find i'th Index character in a binary string obtained after n iterations
- Find a string such that every character is lexicographically greater than its immediate next character
- Find the character in first string that is present at minimum index in second string
- Queries to find the last non-repeating character in the sub-string of a given string
- Queries to find the first non-repeating character in the sub-string of a string
- Find k-th character of decrypted string | Set - 2
- Find one extra character in a string
- Find k'th character of decrypted string | Set 1
- Given a string, find its first non-repeating character
- Find the first repeated character in a string
- Find the Nth occurrence of a character in the given String
- Find the last non repeating character in string
- Find last index of a character in a string
- Find repeated character present first in a string
- Program to find the kth character after decrypting a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.