QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · INTERVIEW · 28 OF 112

SDET Coding Interview Questions in Java, Solved

The coding round of an SDET interview: what it scores, a method for answering out loud, and the classic questions solved in Java with their complexity: reverse words, palindrome, first unique character, anagrams, balanced brackets, second largest and a missing number. Plus the tester twist interviewers love: list your test cases before and after you code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Clarify
  • test cases first
  • plan out loud
  • small methods
  • dry run
  • Big O
  • the seven classics in Java

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.

Six steps, out loud
  • 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.

Cases for "reverse words"
  • "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.

Reverse the words
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.

Is it a palindrome?
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.

First non-repeating char
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.

Are they anagrams?
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.

Balanced brackets
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.

Two array classics
// 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.

Big O in one minute
  • 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.

Finish like a tester
@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.

Avoid these
  • 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.

Your opening lines
  • "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."

Interview questions

Q1How do you reverse the words in a sentence in Java?

Trim, split on "\\s+", reverse the array (Collections.reverse on Arrays.asList) and join with " "; O(n) time and space. Without split, scan from the end with two pointers.

Q2How do you check if a string is a palindrome?

Normalise case and remove non-alphanumerics if required, then compare characters with two pointers moving inward; O(n) time.

Q3How do you find the first non-repeating character?

Count characters in a LinkedHashMap, then return the first key with count 1; O(n) time, O(k) space for k distinct characters.

Q4How do you check whether two strings are anagrams?

Compare lengths, then count letters up for one string and down for the other (int[26] or a map); all counts must end at zero. O(n) time.

Q5How do you check balanced brackets?

Push opening brackets on a stack; for each closing bracket, pop and check it matches; the stack must be empty at the end. O(n).

Q6How do you find the second largest number in an array?

Scan once tracking the largest and second largest distinct values; O(n) time, O(1) space. Clarify duplicates and arrays with fewer than two distinct values.

Q7How do you find the missing number from 1 to n?

Subtract every element from n(n+1)/2 (use long for large n), or XOR all indices and values; O(n) time, O(1) space.

Q8Why list test cases before coding in an SDET interview?

It clarifies requirements, catches edge cases early and shows the testing mindset the role needs; you then use the same cases to dry-run and test your solution.