String indexing (positive and negative) in Python - Time & Space Complexity
When we access characters in a string by their position, it is important to know how fast this operation is.
We want to understand how the time to get a character changes as the string gets longer.
Analyze the time complexity of the following code snippet.
text = "hello world"
char1 = text[2] # positive index
char2 = text[-3] # negative index
print(char1, char2)
This code gets characters from a string using positive and negative positions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing a single character by index in the string.
- How many times: Twice, but each access is independent and direct.
Getting a character by index does not depend on the string length; it is a direct jump.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 |
| 100 | 2 |
| 1000 | 2 |
Pattern observation: The number of operations stays the same no matter how long the string is.
Time Complexity: O(1)
This means accessing a character by index takes the same short time regardless of string length.
[X] Wrong: "Accessing a character by index takes longer if the string is longer."
[OK] Correct: Strings are stored so that each position can be reached directly, so length does not slow down access.
Knowing that string indexing is fast helps you understand how to write efficient code when working with text.
"What if we tried to find a character by searching through the string instead of indexing? How would the time complexity change?"