Challenge - 5 Problems
String Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of character traversal with index increment
What is the output of the following Java code snippet?
DSA Java
public class Main { public static void main(String[] args) { String s = "hello"; StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i += 2) { result.append(s.charAt(i)); } System.out.println(result.toString()); } }
Attempts:
2 left
💡 Hint
Look at how the loop increments the index by 2 each time.
✗ Incorrect
The loop starts at index 0 and increments by 2, so it accesses characters at positions 0, 2, and 4 which are 'h', 'l', and 'o'.
❓ Predict Output
intermediateOutput of reverse string traversal
What will be printed by this Java code?
DSA Java
public class Main { public static void main(String[] args) { String s = "world"; StringBuilder reversed = new StringBuilder(); for (int i = s.length() - 1; i >= 0; i--) { reversed.append(s.charAt(i)); } System.out.println(reversed.toString()); } }
Attempts:
2 left
💡 Hint
The loop goes from the last character to the first.
✗ Incorrect
The loop appends characters starting from the last index to the first, reversing the string.
🔧 Debug
advancedIdentify the error in string character access
What error will this Java code produce when run?
DSA Java
public class Main { public static void main(String[] args) { String s = "abc"; char c = s.charAt(3); System.out.println(c); } }
Attempts:
2 left
💡 Hint
Check the valid index range for the string.
✗ Incorrect
The string "abc" has indices 0,1,2. Accessing index 3 is out of range and throws StringIndexOutOfBoundsException.
❓ Predict Output
advancedOutput of nested loops with string character access
What is the output of this Java code?
DSA Java
public class Main { public static void main(String[] args) { String s = "abc"; StringBuilder output = new StringBuilder(); for (int i = 0; i < s.length(); i++) { for (int j = 0; j <= i; j++) { output.append(s.charAt(j)); } output.append(","); } System.out.println(output.toString()); } }
Attempts:
2 left
💡 Hint
The inner loop prints characters from start up to current outer index.
✗ Incorrect
For i=0 prints 'a', for i=1 prints 'ab', for i=2 prints 'abc', each followed by a comma.
❓ Predict Output
expertOutput after filtering vowels from string
What is the output of this Java code that filters vowels from a string?
DSA Java
public class Main { public static void main(String[] args) { String s = "education"; StringBuilder vowels = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowels.append(c); } } System.out.println(vowels.toString()); } }
Attempts:
2 left
💡 Hint
Only vowels are appended to the result string.
✗ Incorrect
The code appends only vowels found in the string 'education' in order: e, u, a, i, o.
