Data Structures And AlgorithmsUnit 28 min read
Arrays & Strings: Operations, Patterns & Applications
Unit 2 of Data Structures And Algorithms: explores fundamental data structures (arrays and strings), their operations, time-space tradeoffs, and real-world applications in sorting, searching, and text processing—critical for algorithms, databases, and modern apps like eSewa and Daraz.
TAKEAWAYS:
- Arrays store contiguous memory blocks of fixed-size elements, enabling O(1) access but rigid resizing.
- Strings are immutable sequences of Unicode characters, optimized for concatenation and pattern matching.
- Time-space tradeoffs (e.g., O(n²) vs. O(n) sorting) directly impact app performance (e.g., Daraz’s inventory search).
- Pattern matching (KMP, Rabin-Karp) powers eSewa’s fraud detection and Google’s autocomplete.
- Two-dimensional arrays model grids (e.g., Pathao’s route matrices) and sparse matrices (NEPSE stock data).
- String compression (RLE, Huffman) reduces storage in WhatsApp’s media archives.
1. Arrays: Definition and Representation
Arrays are contiguous memory allocations of the same data type, accessed via indices. They support random access (O(1)) but fixed size (unless dynamically resized).
1.1 Static vs. Dynamic Arrays
| Feature | Static Array | Dynamic Array |
|---|---|---|
| Memory | Pre-allocated (fixed size) | Grows/shrinks (e.g., ArrayList in Java) |
| Resizing | Impossible (crashes on overflow) | Expands via doubling (amortized O(1)) |
| Use Case | Small, known datasets (e.g., exam scores) | Large, variable data (e.g., user logs) |
Visual: Static vs. Dynamic Array Growth
2. Array Operations
2.1 Insertion and Deletion
- Insertion at end: O(1) (static) or amortized O(1) (dynamic).
- Insertion at index
i: O(n) (shifts elements). - Deletion at index
i: O(n) (shifts elements).
Worked Example: Insert 7 at index 2 in [1, 3, 5, 7]
Code Trace (Python):
arr = [1, 3, 5, 7]
arr.insert(2, 7) # Insert 7 at index 2
Step-by-Step State:
| Step | Array State | Action |
|---|---|---|
| 1 | [1, 3, 5, 7] |
Insert 7 at index 2 |
| 2 | [1, 3, 7, 5] |
Shift elements right |
2.2 Searching in Arrays
- Linear Search: O(n) (checks each element).
- Binary Search: O(log n) (requires sorted array).
Visual: Binary Search Steps
Code Trace (Binary Search):
def binary_search(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target: return mid
elif arr[mid] < target: left = mid + 1
else: right = mid - 1
return -1
Trace for arr = [2, 5, 8, 12, 16], target = 8:
| Iteration | left | right | mid | arr[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 8 | Found at 2 |
3. Multidimensional Arrays
3.1 Representation
- Row-major order: Elements stored left-to-right, top-to-bottom (e.g., C/Java).
- Column-major order: Elements stored top-to-bottom, left-to-right (e.g., Fortran).
Visual: 2D Array (Row-Major)
Worked Example: Access arr[1][0] in [[1, 2], [3, 4]]
- Address Calculation:
base + (1 * cols + 0) * sizeof(int) - Value:
3
4. Strings: Definition and Operations
Strings are immutable sequences of Unicode characters (e.g., "Nepal").
4.1 String Operations
| Operation | Time Complexity | Example |
|---|---|---|
| Concatenation | O(n) | "Hi" + "Nepal" → "HiNepal" |
| Substring | O(k) | "Nepal"[1:3] → "ep" |
| Reversal | O(n) | "abc" → "cba" |
Visual: String Concatenation (Immutable)
graph TD
A["str1 = \"Hello\""] --> B["str2 = \"World\""]
B --> C["str3 = str1 + str2\nstr3 = \"HelloWorld\""]Code Trace (Python):
s1 = "Hello"
s2 = "World"
s3 = s1 + s2 # Creates new string
Memory Before/After:
Before: s1="Hello", s2="World"
After: s3="HelloWorld" (new allocation)
5. String Matching Algorithms
5.1 Naive String Matching
- Idea: Slide pattern over text, compare characters.
- Time: O(n*m) (worst case).
Visual: Naive Matching for "abba" in "abababba"
Code Trace:
def naive_match(text, pattern):
n, m = len(text), len(pattern)
for i in range(n - m + 1):
if text[i:i+m] == pattern: return i
return -1
Trace for text="abababba", pattern="abba":
| i | text[i:i+4] | Match? |
|---|---|---|
| 0 | "abab" | No |
| 1 | "babab" | No |
| 2 | "ababb" | No |
| 3 | "babba" | No |
| 4 | abba | Yes |
5.2 Knuth-Morris-Pratt (KMP) Algorithm
- Idea: Preprocess pattern to skip unnecessary comparisons.
- Time: O(n + m).
Visual: KMP Failure Function
Code Trace:
def compute_lps(pattern):
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
Trace for pattern="abba":
| i | pattern[i] | length | lps[i] |
|---|---|---|---|
| 1 | 'b' | 0 | 0 |
| 2 | 'b' | 1 | 1 |
| 3 | 'a' | 0 | 0 |
6. Applications of Arrays and Strings
6.1 In the Real World
eSewa’s Transaction Logs
- Idea: Arrays store transaction records (e.g.,
transactions[1000] = {"user": "A", "amount": 500}). - Why: Fast random access to verify fraud (O(1) lookup).
- Idea: Arrays store transaction records (e.g.,
Daraz’s Order Queue
- Idea: Queues (arrays) manage order processing (FIFO).
- Why: Ensures first-order-first-served delivery.
Pathao’s Route Matrix
- Idea: 2D arrays represent distances between stops (e.g.,
matrix[i][j] = time from stop i to j). - Why: Dijkstra’s algorithm (Unit 9) finds shortest routes.
- Idea: 2D arrays represent distances between stops (e.g.,
Worked Example: Daraz Order Queue
7. Time-Space Tradeoffs
| Operation | Time Complexity | Space Complexity | Use Case |
|---|---|---|---|
| Bubble Sort | O(n²) | O(1) | Small datasets |
| Merge Sort | O(n log n) | O(n) | Large datasets (e.g., NEPSE) |
| Hash Table | O(1) avg | O(n) | Fast lookups (e.g., eSewa) |
Visual: Tradeoff Graph
Exam Tip
- Focus Areas:
- Arrays: Insertion/deletion traces, 2D array indexing.
- Strings: Naive vs. KMP matching, substring operations.
- Applications: Link array/string concepts to real apps (eSewa, Daraz).
- Common Mistakes:
- Off-by-one errors in array indices (e.g.,
arr[n-1]vs.arr[n]). - Forgetting immutability of strings in concatenation.
- Off-by-one errors in array indices (e.g.,
- Practice:
- Solve 2-3 problems on array manipulation (e.g., rotate matrix).
- Implement KMP algorithm from scratch and trace it.
Final Note: Arrays and strings are the building blocks of algorithms. Master their operations, tradeoffs, and real-world uses to ace TU/PU exams and design efficient apps!
Based on the TU BCA syllabus for Data Structures And Algorithms (CACS201), unit 2.
Discussion
Loading…