0
0
Kotlinprogramming~5 mins

String methods (substring, split, trim) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String methods (substring, split, trim)
O(n)
Understanding Time Complexity

When working with strings, it is important to know how long operations like cutting parts, splitting, or cleaning spaces take.

We want to understand how the time needed grows as the string gets longer.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


val text = "  apple, banana, cherry, date  "
val trimmed = text.trim()
val parts = trimmed.split(",")
val firstFruit = parts[0].substring(1, 4)
    

This code trims spaces, splits the string by commas, and extracts a substring from the first part.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The split method scans the entire string once to find commas.
  • How many times: It looks at each character once, so it runs about n times, where n is the string length.
How Execution Grows With Input

As the string gets longer, the time to trim and split grows roughly in direct proportion to its length.

Input Size (n)Approx. Operations
10About 10 checks for trim and split
100About 100 checks for trim and split
1000About 1000 checks for trim and split

Pattern observation: The work grows steadily as the string length increases.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line with the string length.

Common Mistake

[X] Wrong: "Splitting a string is instant and does not depend on its length."

[OK] Correct: The split method must check each character to find separators, so it takes longer for longer strings.

Interview Connect

Understanding how string methods work under the hood helps you write efficient code and answer questions about performance clearly.

Self-Check

"What if we used a regular expression with split instead of a simple character? How would the time complexity change?"