Common string methods in Java - Time & Space Complexity
We want to understand how long common string methods take to run as the string gets bigger.
How does the time needed change when the string length grows?
Analyze the time complexity of the following code snippet.
String s = "hello world";
int length = s.length();
char c = s.charAt(3);
String sub = s.substring(0, 5);
boolean contains = s.contains("lo");
String replaced = s.replace('l', 'x');
This code uses common string methods like length, charAt, substring, contains, and replace.
Look at which parts repeat or scan the string.
- Primary operation: Methods like
replaceandcontainsscan the string characters. - How many times: They check each character once, so the number of checks grows with string length.
As the string gets longer, some methods take longer because they look at more characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks for scanning methods |
| 100 | About 100 checks for scanning methods |
| 1000 | About 1000 checks for scanning methods |
Pattern observation: The time grows roughly in direct proportion to the string length for scanning methods.
Time Complexity: O(n)
This means the time needed grows in a straight line as the string gets longer.
[X] Wrong: "All string methods run instantly no matter the string size."
[OK] Correct: Some methods check each character, so longer strings take more time.
Knowing how string methods scale helps you write code that stays fast even with big text data.
"What if we used indexOf instead of contains? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of
Thecontains()contains()method checks if the string includes a specific sequence of characters and returns true or false.Step 2: Compare with other methods
equals()checks full equality,substring()extracts part of a string, andreplace()changes characters. None check for containment.Final Answer:
contains() -> Option BQuick Check:
Check substring presence = contains() [OK]
- Confusing contains() with equals()
- Using substring() to check presence
- Thinking replace() checks for text
str to uppercase in Java?Solution
Step 1: Recall the method name for uppercase conversion
The correct method name in Java String class istoUpperCase(), called on the string object.Step 2: Check syntax correctness
str.toUpperCase(); usesstr.toUpperCase();which is valid. Others use incorrect method names or syntax.Final Answer:
str.toUpperCase(); -> Option AQuick Check:
Uppercase method = toUpperCase() [OK]
- Using uppercase() instead of toUpperCase()
- Calling method without object (toUpperCase(str))
- Using toUpper() which does not exist
String text = "Hello World";
int pos = text.indexOf("World");
System.out.println(pos);Solution
Step 1: Understand what indexOf() does
TheindexOf()method returns the starting index of the substring if found, or -1 if not found.Step 2: Find the position of "World" in "Hello World"
"Hello " has 6 characters (index 0 to 5), so "World" starts at index 6.Final Answer:
6 -> Option AQuick Check:
Substring start index = 6 [OK]
- Confusing index with length
- Expecting index 0 for substring
- Thinking indexOf() returns boolean
String s = "Java Programming"; String part = s.substring(5, 3); System.out.println(part);
Solution
Step 1: Check substring() method argument rules
substring(start, end) requires start index less than or equal to end index; here 5 > 3, which is invalid.Step 2: Confirm other syntax correctness
Semicolons are present, substring() is valid on String, and 'part' is declared properly.Final Answer:
substring() arguments are reversed; start index must be <= end index -> Option CQuick Check:
substring(start, end) needs start ≤ end [OK]
- Swapping start and end indexes
- Thinking substring() changes original string
- Ignoring exception thrown at runtime
input = "apple,banana,orange", which code snippet correctly replaces all commas with semicolons and converts the result to uppercase?Solution
Step 1: Understand replace() vs replaceAll()
Bothreplace()andreplaceAll()can replace characters, butreplaceAll()uses regex and is safer for multiple replacements.Step 2: Check method chaining and correctness
A and B usereplaceFirst()which only replaces the first comma. C uses invalidtoUpper().Step 3: Choose best practice
UsingreplaceAll()with chaining totoUpperCase()is correct and clear.Final Answer:
input.replaceAll(",", ";").toUpperCase(); -> Option DQuick Check:
Replace commas then uppercase = replaceAll + toUpperCase() [OK]
- Using toUpper() instead of toUpperCase()
- Using replaceFirst() which only replaces the first occurrence
- Confusing replace() and replaceAll() usage
Ready to prove it?
Pass the test and this pattern moves unknown
