Coding challenges
In the next 11 coding challenges, we will cover the most popular problems involving stacks and queues that have appeared in interviews in the past few years in a wide range of companies that hire Java developers. One of the most common problems, Implementing three stacks with one array, was covered in Chapter 10, Arrays and Strings.
The solutions to the following coding challenges rely on the Java built-in Stack
and ArrayDeque
APIs. So, let's get started!
Coding challenge 1 – Reverse string
Problem: Consider you've been given a string. Use a stack to reverse it.
Solution: Reversing a string using a stack can be done as follows:
- Loop the string from left to right and push each character into the stack.
- Loop the stack and pop the characters one by one. Each popped character is put back into the string.
The code based on these two steps is as follows:
public static String reverse(String str) { Â Â Stack<Character...