Array ( [0] => [1] => questions [2] => Strings [3] => Remove-adjacent-duplicates )
Given a string K. You have to remove all the adjacent duplicate values in given string.
First line contains the string K.
Print the string after removing adjacent duplicates.
abaa
aba
abbaa
aba
abcd
abcd
Login to see Discussion
Approach 1: using two loops
step-i) convert given string to character array as strings are immutable
step-ii) get the length of the string
step-iii)assign 0 to i
step-iv) check if character at index i and index i+1 are same or not
step-v) if same move all the elements to left by one postion and decrement the length by one value
step-vi)increment i value by one
step-vii) repeat steps iv to vi still i is less than the value of length
step-step-viii) create a empty string answer and concatinat all the characters of the array to it
step-ix) return answer
Time Complexity: O(n^2)
Space Complexity: O(n)
Approach and Analysis:
step-i) convert given string to character array
step-step-step-ii)assign null to prev which is character
step-step-iii)assign 0 to k which is a integer
step-iv) traverse the character array and check if adjacent elements are same or not
step-v)if they are not same append that character to the array increment k value and assign that character to prev
step-vi) convert that character array to string
step-vii)return the substring of the converted string from 0 to k
Time Complexity: O(n)
Space Complexity: O(n)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution