DSA SERIES – Chapter 3: STRINGS (Python Version)

 


[Follow here] for daily coding insights.

DSA SERIES – Chapter 3: STRINGS (Python Version)


1. What is a String in Python?

In Python:

  • String = Immutable sequence of Unicode characters

  • Internally stored as an array of characters

  • Since strings are immutable, any modification creates a new string in memory

Example:

s = "Hello"

2. Memory Representation (Very Important)

Python strings use:

  • Unicode encoding

  • Immutable memory blocks

  • String interning (optimization where Python reuses identical string objects)

Example:

a = "hello"
b = "hello"
print(a is b)  # True (interned)

3. String Declaration

s1 = "Python"
s2 = 'DSA'
s3 = """Multi-line 
string"""

Python allows:
✔ Single quotes
✔ Double quotes
✔ Triple quotes (multi-line)


4. Accessing Characters (Indexing)

Python supports:

  • Positive indices (0 → n-1)

  • Negative indices (-1 → last element)

s = "HELLO"
print(s[0])   # H
print(s[-1])  # O

5. Slicing (Very Common in DSA)

s = "ABCDEFG"
print(s[1:5])   # BCDE
print(s[:4])    # ABCD
print(s[3:])    # DEFG
print(s[::-1])  # reverse

6. Strings Are Immutable

You cannot modify a character:

s = "hello"
s[0] = 'Y'     #  Error

To “modify” → create a new string:

s = "hello"
s = 'Y' + s[1:]
print(s)       # Yello

7. String Operations

✔ len()

len("Python")  # 6

✔ Concatenation

"Hello" + "World"

✔ Repetition

"Hi" * 3   # HiHiHi

✔ Membership

print("Py" in "Python")   # True

8. Useful Built-In String Methods

Changing Case

s.lower()
s.upper()
s.title()
s.capitalize()

Checking Content

s.isalpha()
s.isdigit()
s.isalnum()
s.isupper()
s.islower()
s.isnumeric()

Searching

s.find("on")     # returns index or -1
s.rfind("on")
s.startswith("Py")
s.endswith("on")

Replace

s.replace("a", "AA")

Splitting & Joining

s.split()
" ".join(["A","B","C"])

9. Iterating Through a String

for ch in "Hello":
    print(ch)

10. Converting Between Strings and Other Types

int("123")
str(1010)
list("Python")

11. Time Complexities (Python String Ops)

Operation Time
Access char O(1)
Search substring O(n)
Concatenation O(n)
Slicing O(k) (k = sliced length)
Reversing O(n)
Split O(n)
Replace O(n)

Reason: Due to immutability, new strings must be created.


12. Common DSA-Level String Problems

✔ Reverse a string

s[::-1]

✔ Check palindrome

s == s[::-1]

✔ Count vowels

sum(1 for c in s if c.lower() in 'aeiou')

✔ Frequency count

from collections import Counter
Counter(s)

✔ Remove duplicates (maintain order)

result = ""
for ch in s:
    if ch not in result:
        result += ch

13. 20 Practice Questions (Python Edition)

Questions

  1. What is a string in Python?

  2. Are strings mutable or immutable?

  3. How does slicing work?

  4. How to reverse a string in one line?

  5. Difference between find() and index().

  6. Write code to count vowels.

  7. How to check if a string is palindrome?

  8. Explain negative indexing.

  9. Write code to remove duplicates.

  10. What is string interning?

  11. Why is concatenation O(n)?

  12. How to split a string into words?

  13. How to join a list into a string?

  14. Write code to check if two strings are anagrams.

  15. Write code to count words.

  16. Difference between isdigit() and isnumeric().

  17. Write code to find frequency of characters.

  18. Explain difference between == and is.

  19. Why slicing does not modify original string?

  20. Write code to convert string to list of characters.


Answers

  1. Immutable sequence of Unicode characters.

  2. Immutable.

  3. s[start:end:step]

  4. s[::-1]

  5. index() throws error; find() returns -1.

  6. Loop & count aeious.

  7. Compare with reverse.

  8. Negative values index from end.

  9. Loop and add if not present.

  10. Optimization where identical strings share memory.

  11. New string created → copying cost.

  12. Using split().

  13. Using join().

  14. Sort both strings or use Counter.

  15. split() + len().

  16. isnumeric() supports more Unicode digits.

  17. Using Counter.

  18. == compares value, is compares identity.

  19. Strings immutable → slice creates new string.

  20. list(s)

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)


DSA Series Chapter 3 Strings (C Version)






Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights.

Comments