Skip to main content
All Questions

How would you remove duplicates in a string?

Medium
Unlock detailed company stats for this questionUpgrade

Remove Adjacent Duplicates in String. You are given a string s and an integer k. Write a function to remove k adjacent duplicates from s where the "adjacent" characters are equal.

For instance, if k is 3 and the string is "daaabbbaa", since we have "aaa" and "bbb" as adjacent triples, the function should transform the string to "daa", removing the "bbb" first and then the remaining "aaa".

Examples

s = 'abcd' k = 2 output: 'abcd' s = 'deeedbbcccbdaa' k = 3 output: 'aa' s = 'pbbcggttciiippooaais' k = 2 output: 'ps' s = 'aaabbbacd' k = 3 output: 'acd'

In each example, output refers to the resulting string after all possible k adjacent duplicates have been removed.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.