Skip to content

Commit 58f6885

Browse files
authored
Add algorithmic space optimization notes for LCS
Added notes on algorithmic space optimization for LCS in embedded systems, detailing the challenge and a bitwise solution to reduce space complexity.
1 parent 8ac10f5 commit 58f6885

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

docs/algorithm_notes.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 🧮 Algorithmic Space Optimization Note
2+
3+
## The Challenge
4+
The standard Longest Common Subsequence (LCS) algorithm relies on dynamic programming. For two sequences of lengths $m$ and $n$, it constructs a 2D matrix of size $(m+1) \times (n+1)$.
5+
6+
In typical desktop environments, this is trivial. However, in embedded systems like the ATmega328P with only 2KB of SRAM, calculating the LCS for a 100-character string and a 120-character string requires `100 * 120 * 2 bytes = 24,000 bytes` (24KB), which results in an immediate memory crash.
7+
8+
## The Bitwise Solution
9+
If we observe the DP state transition:
10+
`L[i][j] = L[i-1][j-1] + 1` (if characters match)
11+
`L[i][j] = max(L[i-1][j], L[i][j-1])` (if they don't match)
12+
13+
We realize that calculating the current row `i` ONLY requires the values from the current row `i` and the previous row `i-1`. The rest of the matrix is useless after the calculation moves forward.
14+
15+
By reducing the matrix to `L[2][n+1]` and using the bitwise AND operator `i & 1` to switch between row `0` and row `1`, we reduce the space complexity from $O(m \times n)$ to $O(\min(m, n))$.
16+
17+
This optimization allows the micro-controller to process much larger configuration files without exceeding its strict memory limits.

0 commit comments

Comments
 (0)