π String Copy (Under String Operations in Data Structures)
String Copy is a basic string operation where the contents of one string are duplicated into another string.
Example:
Source: "HELLO"
Destination: "HELLO"
In Data Structures, strings behave like arrays of characters, so copying involves copying each character sequentially.
π Why String Copy Matters in DSA?
- Strings are stored as sequences in memory
- Copying determines space and time complexity
- Strings are immutable in Python β you canβt modify them directly
- Many algorithms use copy operations internally:
- Substring creation
- Concatenation
- Dynamic resizing
- Buffer operations
π What Happens During String Copy? (Conceptual)
For a string of length n, copying involves:
- Allocating memory for the new string
- Copying each character one by one
- Adding a null terminator (
\0) in languages like C - Returning the address of the new string
Time Complexity
[
O(n)
]
Because each of the n characters must be copied.
π String Copy in Python
Python strings are immutable, so copying does not copy character-by-character unless necessary.
Case 1: Direct Assignment
a = "hello"
b = a
β No new copy
β Both refer to the same string object
β O(1) time
This is reference copying, not content copying.
Case 2: Full Content Copy (actual cloning)
a = "hello"
b = a[:]
c = str(a)
d = "".join(a)
β Creates a new string object
β Time complexity = O(n)
π Python Examples of String Copy
β Simple copy using slicing
s1 = "DataStructure"
s2 = s1[:] # full copy
print(s2)
β Using str()
s1 = "Python"
s2 = str(s1) # creates a new copy
β Manual character-by-character copy (DSA-style)
s1 = "HELLO"
s2 = ""
for ch in s1:
s2 += ch # O(nΒ²) inefficient
Why O(nΒ²)?
- Because each
+=creates a new string β copying repeatedly.
Better approach:
s1 = "HELLO"
temp = []
for ch in s1:
temp.append(ch)
s2 = "".join(temp) # O(n)
π String Copy in Memory (DSA View)
Consider:
char s1[] = "ABC";
char s2[4];
Copy steps:
- s2[0] = s1[0] β ‘A’
- s2[1] = s1[1] β ‘B’
- s2[2] = s1[2] β ‘C’
- s2[3] = ‘\0’
Same idea applies conceptually, even though Python abstracts it.
π Applications of String Copy
- Creating new buffers
- Returning substrings
- Editing strings in memory
- String manipulation algorithms:
- pattern matching
- string reverse
- concatenation
- encryption/encoding
π Efficiency Concerns
| Method | Description | Time |
|---|---|---|
| Direct assignment | No new copy | O(1) |
Slicing ([:]) | Full copy | O(n) |
str() | Full copy | O(n) |
"".join(list) | Efficient building | O(n) |
+= in loop | Slow repeated copying | O(nΒ²) |
For large strings, always avoid += inside loops.
π Summary (Exam Notes)
- String Copy = duplication of one string into another
- Conceptually: copy characters sequentially
- Time complexity = O(n)
- Python strings are immutable, assignment only copies reference
- Full copies use slicing, join, or
str() - Avoid repeated concatenations β expensive O(nΒ²)
