Notes
The method
Use the same six steps for every question, out loud. Clarify: what exactly is the input and output, how big, does case matter, what about spaces and empty input? List test cases, which is where a tester can shine. Say your approach before coding. Code in small, well named methods. Dry run your test cases through the code. And state the time and space complexity. Interviewers score your thinking, so never go silent.
- 1 clarify: input, output, size, case, spaces, empty?
- 2 list test cases (you are a tester: show it)
- 3 say the approach first
- 4 code in small methods
- 5 dry run your cases
- 6 time and space complexity
- silence is the enemy
The tester twist
Here is the twist. Before you write a line, list test cases. For reversing the words of a sentence: a normal sentence, one word, an empty string, extra spaces at the ends and between words, punctuation, null, and a very long input. Several of these are really questions: should extra spaces be kept? Asking them shows exactly the skill the job needs. Developers often forget this step. SDET candidates should never skip it.
- "ship it" → "it ship"
- one word "ship" → "ship"
- empty "" → ""
- spaces " ship it " → "it ship" (ask!)
- punctuation "hi, there"
- null → error or ""? (ask)
- very long input: performance
- questions = clarification
Reverse words
Reverse the words. Trim the ends, split on one or more whitespace characters, reverse the array through a list view, and join with single spaces. For space ship it, several spaces, on friday space, you get friday on it ship. Time is O of n, because each character is touched a constant number of times, and space is O of n for the words. A follow up often asks you to do it without split, with two pointers; practise both.
static String reverseWords(String s)
{
String[] w = s.trim()
.split("\\s+");
Collections.reverse(
Arrays.asList(w));
return String.join(" ", w);
}
// " ship it on friday "
// → "friday on it ship"
// time O(n), space O(n) Palindrome
Is it a palindrome? First clarify: ignore case and punctuation? Usually yes. Normalise to lower case letters and digits, then walk two pointers in from both ends, comparing characters. Never odd or even is a palindrome; ShopRung is not. Time O of n. The pointer loop needs constant extra space, though the cleaned copy uses O of n; mention that you could skip non letters in place to avoid the copy.
static boolean isPalindrome(
String s) {
String t = s.toLowerCase()
.replaceAll("[^a-z0-9]", "");
int i = 0, j = t.length() - 1;
while (i < j)
if (t.charAt(i++) !=
t.charAt(j--)) return false;
return true;
}
// "Never odd or even" → true First unique
First non repeating character. Count characters with a linked hash map, which keeps first seen order, then return the first key with a count of one. In testing, t appears twice, so the answer is e. In a a b b, there is none, so we return null; say that you would agree with the interviewer what to return. Two passes, so O of n time, and the map holds at most the alphabet size.
static Character firstUnique(
String s) {
Map<Character, Integer> c =
new LinkedHashMap<>();
for (char ch : s.toCharArray())
c.merge(ch, 1, Integer::sum);
for (var e : c.entrySet())
if (e.getValue() == 1)
return e.getKey();
return null; }
// "testing" → e "aabb" → null Anagrams
Are two words anagrams? If the lengths differ, no. Otherwise keep twenty six counters, one per letter: add one for each letter of the first word and subtract one for the second. If every counter ends at zero, they are anagrams. Listen and silent are; rung and ring are not. O of n time and constant space. Clarify that it assumes lower case English letters; for any text, use a map instead of the array.
static boolean anagram(String a,
String b) {
if (a.length() != b.length())
return false;
int[] n = new int[26];
for (int i = 0; i < a.length(); i++)
{ n[a.charAt(i) - 'a']++;
n[b.charAt(i) - 'a']--; }
for (int x : n) if (x != 0)
return false;
return true; } // listen, silent Brackets
Balanced brackets uses a stack. Push every opening bracket. For a closing bracket, the stack must not be empty, and the bracket on top must be the matching opener. At the end, the stack must be empty. Curly, square, round, then closed in reverse, is balanced. Round, square, round close, square close is not, because they cross. Two round openers alone are not, because the stack is left with two. O of n time and space.
Deque<Character> st =
new ArrayDeque<>();
for (char c : s.toCharArray()) {
if ("([{".indexOf(c) >= 0)
st.push(c);
else if (")]}".indexOf(c) >= 0) {
if (st.isEmpty()) return false;
if ("([{".indexOf(st.pop()) !=
")]}".indexOf(c)) return false;
} }
return st.isEmpty(); Arrays
Two array classics. Second largest: keep the largest and second largest while scanning once, ignoring duplicates of the largest. In these ShopRung prices, the headphones appear twice, so the second largest distinct value is twenty five fifty. Missing number from one to n: the sum of one to n is n times n plus one over two; subtract every number present, and what is left is missing. One, two, four, five gives three. Ask about duplicates and overflow.
// second largest DISTINCT value // [1500, 499, 12999, 2550, 12999] // → 2550 (track top two) // missing number in 1..n int sum = n * (n + 1) / 2; for (int x : a) sum -= x; // [1, 2, 4, 5], n = 5 → 3 both O(n) time, O(1) space ask: duplicates? overflow?
Complexity
State the cost of every solution in Big O. Constant, logarithmic when you halve the work each step, linear for one pass, n log n for sorting, and quadratic for a loop inside a loop. If you are stuck, say a brute force solution first, then improve it: this is O of n squared, and with a hash map it becomes O of n time and O of n space. Interviewers care more about this reasoning than about a perfect first answer.
- O(1) constant
- O(log n) halve each step
- O(n) one pass
- O(n log n) sorting
- O(n²) a loop in a loop
- brute force first if stuck, then improve: "this is O(n²);
- with a HashMap it becomes
- O(n) time, O(n) space"
Check your code
Finish like a tester. Dry run your listed cases through the code, line by line, out loud. Then, if there is time, turn the cases into a parameterized JUnit test, like the rows here for reversing words. Very few candidates do this, and it directly shows the job: you write code and you prove it works. Then practise more problems like these in the DSA section of this site.
@ParameterizedTest
@CsvSource({
"ship it, it ship",
"ship, ship",
"' ship it ', it ship"
})
void reverses(String in,
String out) {
assertEquals(out,
reverseWords(in));
} Common mistakes
How candidates lose the coding round. Coding before clarifying. Long silences. Ignoring edge cases like empty input, null, a single item or extra spaces. One giant method nobody can follow. Comparing strings with double equals. Never tracing an example through the code. And forgetting to state the complexity. Each of these is easy to fix with the six step method and a little practice.
- coding before clarifying
- silence for minutes
- no edge cases (empty, null, one item, spaces)
- one giant method
- == on strings
- never running through an example
- no complexity at the end
Say it like this
Open every coding question the same way. Restate the problem in your own words. Ask: can the input be empty or null, is it case sensitive, how large can it be? List your test cases: normal, empty, one item, duplicates, spaces. Describe the approach and its complexity, for example a hash map count in O of n. Then say: I will code it, then trace these cases. That opening alone puts you ahead of most candidates.
- "Let me restate it: ...
- Can the input be empty or null? Is it case-sensitive?
- How large can it be?
- My test cases: normal, empty, one item, duplicates, spaces.
- Approach: a HashMap count, O(n) time, O(n) space.
- I will code it, then trace
- these cases."