String Traversal and Character Access in DSA Typescript - 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.
function printChars(str: string): void {
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
}
This code goes through each letter in the string and prints it one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each character in the string inside the loop.
- How many times: Once for every character in the string.
As the string gets longer, the number of steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character accesses and prints |
| 100 | 100 character accesses and prints |
| 1000 | 1000 character accesses and prints |
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 as the string gets longer.
[X] Wrong: "Accessing characters inside a string is instant and does not add to time."
[OK] Correct: Each character access happens one by one, so more characters mean more time.
Knowing how string traversal time grows helps you explain how your code handles longer inputs clearly and confidently.
"What if we used two nested loops to compare every character with every other character? How would the time complexity change?"
Practice
str[2] return when str = "hello"?Solution
Step 1: Understand string indexing
Strings in TypeScript can be accessed by index starting at 0, so index 2 refers to the third character.Step 2: Identify the character at index 2 in "hello"
The characters are: h(0), e(1), l(2), l(3), o(4). So index 2 is 'l'.Final Answer:
The character 'l' -> Option BQuick Check:
str[2] = 'l' [OK]
- Thinking index starts at 1
- Confusing character with substring
- Assuming strings are not indexable
text in TypeScript?Solution
Step 1: Understand looping over strings
Usingfor...ofloops over characters directly, which is the cleanest way.Step 2: Evaluate the options
The index-based loop using <= text.length causes an out-of-bounds access.for...initerates over string indices ('0', '1', etc.) rather than characters.for...ofcorrectly iterates over characters. Starting the index at 1 skips the first character and risks out-of-bounds.Final Answer:
for (let char of text) { console.log(char); } -> Option AQuick Check:
Use for...of to access characters directly [OK]
- Using for...in which loops keys, not values
- Starting index at 1 instead of 0
- Confusing index with character in loops
const s = "abcde";
let result = "";
for (let i = 0; i < s.length; i += 2) {
result += s[i];
}
console.log(result);Solution
Step 1: Analyze the loop increments and indexing
The loop starts at 0 and increments by 2 each time, so indexes are 0, 2, 4.Step 2: Collect characters at indexes 0, 2, 4
Characters are s[0] = 'a', s[2] = 'c', s[4] = 'e'. Concatenated result is "ace".Final Answer:
"ace" -> Option DQuick Check:
Indexes 0,2,4 characters combined = "ace" [OK]
- Assuming loop increments by 1
- Confusing indexes with characters
- Expecting all characters concatenated
word:const word = "test";
for (let i = 1; i <= word.length; i++) {
console.log(word[i]);
}Solution
Step 1: Check loop index range
The loop starts at 1 and goes up to word.length (4), so indexes accessed are 1,2,3,4.Step 2: Identify indexing issues
Index 0 is skipped (first character 't'), and index 4 is out of bounds (undefined). So first character is missed and last access is invalid.Final Answer:
Indexing starts at 1, skipping first character and causing undefined at end -> Option CQuick Check:
String indexes start at 0, not 1 [OK]
- Starting loop at 1 instead of 0
- Using <= instead of < in loop condition
- Assuming strings are not indexable
input, which code snippet correctly reverses the string by traversing it from end to start?Solution
Step 1: Understand correct index range for reverse traversal
Indexes go from input.length - 1 down to 0 inclusive to cover all characters in reverse.Step 2: Verify the index ranges
Looping frominput.length - 1down to 0 inclusive correctly captures all characters in reverse. A forward loop usinginput.length - ifirst accesses an out-of-bounds index. Starting atinput.lengthimmediately accesses invalid index. Decrementing frominput.lengthto 0 also starts with out-of-bounds.Final Answer:
let rev = ''; for (let i = input.length - 1; i >= 0; i--) { rev += input[i]; } console.log(rev); -> Option AQuick Check:
Loop from length-1 down to 0 for reverse traversal [OK]
- Starting loop at length instead of length-1
- Using wrong index inside loop causing undefined
- Loop condition off by one causing missing characters
Ready to prove it?
Pass the test and this pattern moves unknown
