String Traversal and Character Access in DSA Java - Time & Space Complexity
We want to understand how long it takes to look at each letter in a word or sentence.
How does the time grow when the word gets longer?
Analyze the time complexity of the following code snippet.
String text = "hello";
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
System.out.print(c + " ");
}
This code goes through each letter in the string and prints it out.
- Primary operation: Accessing each character in the string one by one.
- How many times: Once for every character in the string.
As the string gets longer, the number of steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character accesses |
| 100 | 100 character accesses |
| 1000 | 1000 character accesses |
Pattern observation: The work grows directly with the length of the string.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the string length.
[X] Wrong: "Accessing each character is instant no matter the string size."
[OK] Correct: Each character must be checked one by one, so longer strings take more time.
Knowing how string traversal time grows helps you write clear and efficient code when working with text data.
"What if we used nested loops to compare every character with every other character? How would the time complexity change?"
Practice
charAt() method do when used on a Java String?Solution
Step 1: Understand the purpose of
ThecharAt()charAt()method is designed to access a single character at a given index in a string.Step 2: Compare with other string methods
Methods likelength()return the string length,toUpperCase()changes case, andsplit()divides the string. These are different fromcharAt().Final Answer:
Returns the character at a specified index in the string -> Option AQuick Check:
charAt()= character access [OK]
- Confusing charAt() with length()
- Thinking charAt() splits the string
- Assuming charAt() changes string case
str in Java?Solution
Step 1: Understand string indexing in Java
String indices start at 0 and go up to length - 1. So loop must run from 0 to less than length.Step 2: Check loop conditions
for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } usesi < str.length(), which correctly stops before index equals length. Options B and D use <= which causes out-of-bounds error. Options C and D start at 1, skipping first character.Final Answer:
for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } -> Option CQuick Check:
Loop from 0 to length-1 [OK]
- Using <= instead of < causing index error
- Starting loop at 1 skipping first char
- Confusing string length with last index
String s = "hello";
for (int i = 0; i < s.length(); i++) {
if (i % 2 == 0) {
System.out.print(s.charAt(i));
}
}Solution
Step 1: Identify loop and condition
The loop runs from i=0 to 4 (length 5). It prints characters only when i is even (0,2,4).Step 2: Find characters at even indices
Index 0: 'h', Index 2: 'l', Index 4: 'o'. These characters are printed in order.Final Answer:
hlo -> Option BQuick Check:
Even indices chars = hlo [OK]
- Printing all characters ignoring condition
- Confusing even and odd indices
- Off-by-one errors in loop
String text = "abc";
for (int i = 0; i <= text.length(); i++) {
System.out.print(text.charAt(i));
}
What error will occur when running this code?Solution
Step 1: Analyze loop bounds
The loop runs from i=0 to i=3 (because of <= and length=3). Valid indices are 0,1,2 only.Step 2: Identify error cause
At i=3,charAt(3)is called, which is out of string bounds, causingStringIndexOutOfBoundsException.Final Answer:
StringIndexOutOfBoundsException -> Option AQuick Check:
charAt index out of range causes StringIndexOutOfBoundsException [OK]
- Confusing StringIndexOutOfBoundsException with ArrayIndexOutOfBoundsException
- Assuming no error occurs
- Thinking NullPointerException will happen
input = "a1b2c3d4", which code snippet correctly extracts and prints only the digits in order?Solution
Step 1: Understand the goal
We want to print only digits from the string, ignoring letters.Step 2: Check each option's condition
for (int i = 0; i < input.length(); i++) { if (Character.isLetter(input.charAt(i))) System.out.print(input.charAt(i)); } usesCharacter.isLetter(), prints letters. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z') System.out.print(input.charAt(i)); } checks lowercase letters range, prints letters. for (int i = 0; i < input.length(); i++) { System.out.print(input.charAt(i)); } prints all characters. for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= '0' && input.charAt(i) <= '9') System.out.print(input.charAt(i)); } checks if char between '0' and '9', prints "1234" correctly.Final Answer:
for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= '0' && input.charAt(i) <= '9') System.out.print(input.charAt(i)); } -> Option DQuick Check:
Check char between '0' and '9' to find digits [OK]
- Printing letters instead of digits
- Printing all characters without filtering
- Using wrong character range for digits
Ready to prove it?
Pass the test and this pattern moves unknown
