Grokking Meta Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
Use an ArrayDeque so that the code leverages modern Java API

Davide Pugliese

Feb 13, 2024

In my view, even in Java, as for Python (where you have syntactic sugar like list comprehensions and tuple unpacking for example), the solution should leverage the language specific API.

In modern Java we don't use Stack anymore, so ArrayDeque should be used. In Java ArrayDeque is a double-ended queue that can be used to add elements to the head or to the tail and remove elements from the head and from the tail. Unlike LinkedList, ArrayDeque guarantees to retrieve the elements in the same order as they were entered when using an iterator (for loop).

import java.util.*; import java.util.stream.*; public class Solution { public String simplifyPath(String path) { Deque<String> stack = new ArrayDeque<>(); var patWoSlash = path.split("/"); for (String s : patWoSlash) { if (!stack.isEmpty() && s.equals("..")) { stack.pop(); } else if (stack.isEmpty() && s.equals("..")) { continue; } else if (!s.isEmpty() && !s.equals(".")) { stack.push(s); } } // Rather than using an additional stack I can leverage the ArraDeque interface that allows me to remove // the last element. In Java when using ArrayDeque as stack, elements are added to the head and removed from the head. // This line avoids creation of an additional stack to retrieve the input elements as they were entered. return stack.isEmpty() ? "/" : stack.stream().map(x-> "/" + stack.pollLast()).collect(Collectors.joining("")); } }

When you have a bunch of elements, like tens of thousands, ArrayDeque performs also better than LinkedList.

Imho, since for senior roles knowledge of the specific Java API is also required, this answer would show that you really know Java besides having a solid algorithmic foundation.

For junior roles you will be totally fine using 2 ArrayDeque (the second to reverse the elements and bring them in the original order).

Using ArrayDeque as in the example imho avoids additional questions regarding Stream API. It's just my humble view, obviously, based on past interviews.

Also, one more thing would be that using nested if statements when you use SonarQube is marked as a bad practice, so the interviewer could think you don't care about code clarity. The rationale is that according to SonarQube nested if statements make the code more complex.

Yes, it's a lot of details that now are required which go beyond the simple solution for senior roles.

0

0

Comments
Comments

On this page