702821. String Manipulation

Easy

String Manipulation

Slug: string-manipulation3706 Difficulty: Easy Id: 702821 Topic Tags: Arrays, Stack, Data Structures

Summary

The problem involves manipulating a given string by performing various operations such as removing duplicates, reversing the string, and checking for palindrome. The key concepts involved are arrays and data structures.

Detailed Explanation

To solve this problem, we can use a stack to keep track of characters in the string. We iterate through the string from left to right, adding each character to the stack. If a character is already present in the stack, we remove it, effectively removing duplicates. After processing the entire string, we pop off all the remaining characters from the stack and concatenate them to form the reversed string.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through the input string from left to right.
  3. For each character, add it to the stack if it is not already present in the stack (to remove duplicates).
  4. After processing the entire string, pop off all the remaining characters from the stack and concatenate them to form the reversed string.

Time complexity analysis: O(n), where n is the length of the input string. We iterate through the string once, so the time complexity is linear. Space complexity analysis: O(n), as we need to store the entire string in the stack (or an equivalent data structure).

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        String str = "hello";
        Stack<Character> stack = new Stack<>();
        
        for (char c : str.toCharArray()) {
            if (!stack.contains(c)) {
                stack.push(c);
            }
        }
        
        StringBuilder reversedStr = new StringBuilder();
        while (!stack.isEmpty()) {
            reversedStr.append(stack.pop());
        }
        
        System.out.println("Reversed string: " + reversedStr.toString());
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.