String slicing and indexing in Ruby - Time & Space Complexity
We want to understand how the time it takes to get parts of a string changes as the string gets bigger.
How does slicing or picking characters from a string grow with the string size?
Analyze the time complexity of the following code snippet.
str = "hello world"
slice = str[2..5]
char = str[4]
This code takes a part of the string from index 2 to 5 and also picks a single character at index 4.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Extracting a substring by copying characters from the original string.
- How many times: The number of characters copied equals the length of the slice requested.
When you ask for a slice of length k, the program copies k characters. So the time depends on how big the slice is, not the whole string.
| Input Size (n) | Approx. Operations for slice length k |
|---|---|
| 10 | Copy k characters (e.g., 4) |
| 100 | Copy k characters (still 4 if slice length same) |
| 1000 | Copy k characters (still 4 if slice length same) |
Pattern observation: Time grows with the slice length, not the total string length.
Time Complexity: O(k)
This means the time depends on how many characters you want to get, not how long the whole string is.
[X] Wrong: "Getting a single character from a string takes time proportional to the whole string length."
[OK] Correct: Accessing one character by index is very fast and does not depend on string size; it is a direct lookup.
Knowing how string slicing works helps you write efficient code when working with text, which is common in many programming tasks.
"What if we sliced the entire string instead of a small part? How would the time complexity change?"
Practice
str[0] return when str = "hello"?Solution
Step 1: Understand Ruby string indexing
Ruby strings are indexed starting at 0, so the first character is at index 0.Step 2: Apply indexing to the string 'hello'
Accessingstr[0]returns the first character 'h'.Final Answer:
The first character of the string, 'h' -> Option AQuick Check:
Index 0 = 'h' [OK]
- Thinking indexing starts at 1
- Expecting the whole string instead of one character
- Confusing last character with first
str = "hello" using slicing?Solution
Step 1: Understand slicing syntax
In Ruby,str[start, length]extracts a substring starting atstartwithlengthcharacters.Step 2: Extract 'ell' from 'hello'
'ell' starts at index 1 and has length 3, sostr[1,3]returns 'ell'.Final Answer:
str[1,3] -> Option AQuick Check:
Substring from index 1, length 3 = 'ell' [OK]
- Using range with wrong end index
- Confusing start and length parameters
- Using negative indices incorrectly
str = "programming" puts str[-4, 3]
Solution
Step 1: Understand negative indexing and slicing
Negative index -4 means counting from the end: 'g'( -1), 'n'( -2), 'i'( -3), 'm'( -4). So index -4 points to 'm'.Step 2: Extract substring starting at 'm' with length 3
From 'm' take 3 characters: 'm', 'i', 'n' forming 'min'.Final Answer:
min -> Option DQuick Check:
str[-4,3] = 'min' [OK]
- Confusing negative index position
- Using range instead of start,length
- Off-by-one errors in slicing length
str = "example" puts str[2..5, 2]
Solution
Step 1: Analyze slicing syntax used
The code usesstr[2..5, 2]which mixes range and length parameters incorrectly. Ruby does not support this syntax.Step 2: Understand correct slicing methods
Use eitherstr[2..5]for range orstr[2, 2]for start and length. Mixing both causes a syntax error.Final Answer:
SyntaxError due to wrong slicing syntax -> Option CQuick Check:
Invalid slice syntax = SyntaxError [OK]
- Mixing range and length in one slice
- Expecting multiple parameters in range slice
- Ignoring Ruby's slice method rules
str = "abracadabra", which code extracts every second character starting from index 0 to index 8 (inclusive)?Solution
Step 1: Understand Ruby slicing limitations
Ruby's slice method does not support step values like Python. Sostr[0, 8, 2]orstr[0..8][::2]are invalid.Step 2: Use chars with index filtering to pick every second character
str[0..8]gets substring 'abracadab'. Thenchars.select.with_index { |_, i| i.even? }picks characters at even indices: a (0), r (2), c (4), d (6), b (8). Joining gives 'ar cdb' without spaces: 'arcdb'.Final Answer:
str[0..8].chars.select.with_index { |_, i| i.even? }.join -> Option BQuick Check:
Use chars and select.with_index for stepping [OK]
- Trying Python-style slicing with step
- Using invalid slice parameters
- Not converting string to chars before filtering
Ready to prove it?
Pass the test and this pattern moves unknown
