Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Sprint-2/improve_with_precomputing/CHANGES_MADE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Changes Made: Optimization via Pre-computing

## Overview
These changes apply the strategy of **Pre-computing**: doing work upfront (like sorting or indexing) to make the primary search or calculation significantly faster. This allowed both algorithms to scale from small examples to datasets containing millions of items.

---

## 1. Longest Common Prefix Optimization (`common_prefix.py`)

### The Problem
The original implementation used a nested loop to compare every string in a list against every other string.
- **Original Complexity**: $O(N^2)$.
- **The Bottleneck**: With 1,000,000 strings, the code would perform roughly 1 trillion comparisons, causing it to hang indefinitely.

### The Solution: "Sort Before Search"
I implemented alphabetical sorting as a pre-computation step.
- **Why it works**: In a sorted list, the strings that share the longest common prefixes are mathematically guaranteed to be **neighbors**.
- **The Change**: By sorting the list first, I replaced the nested loop with a single pass that only compares each string to the one immediately following it.
- **Improved Complexity**: $O(N \log N)$ for the sort + $O(N)$ for the single-pass search.
- **Legacy Retention**: Kept the original `find_common_prefix` helper function and variable names (`longest`, `string`, `other_string`) to maintain code continuity.

---

## 2. Count Letters Optimization (`count_letters.py`)

### The Problem
The original code contained a "hidden loop" inside a string iteration.
- **Original Complexity**: $O(N^2)$.
- **The Bottleneck**: The check `if letter.lower() not in s` required the computer to scan the entire string `s` for every character. On a 10-million-character string, this resulted in an impossible amount of work.

### The Solution: "Sets for Instant Lookups"
I introduced a pre-computed **Set** to handle character lookups.
- **Why it works**: Searching for an item in a Python `set` (a hash table) takes **O(1) constant time**, whereas searching a `string` takes **O(N) linear time**.
- **The Change**: I converted the string `s` into a set (`chars_in_string`) at the start of the function. This one-time $O(N)$ operation transformed the inner search from a slow scan into an instant lookup.
- **Improved Complexity**: $O(N)$ — one pass to build the set, and one pass to loop through the string.
- **Legacy Retention**: Preserved the original loop structure (`for letter in s`), the `is_upper_case` helper, and the `only_upper` variable name.

---

## 3. Technical Trade-offs: Space vs. Time
Both tasks are classic examples of the **Space-vs-Time trade-off**:

1. **Memory (Space)**: We used extra memory to store a sorted version of the list (Task 5) and a set of unique characters (Task 6).
2. **Speed (Time)**: By "spending" this memory, we drastically reduced the number of CPU operations required.

**Result**: Operations that previously would have taken hours now complete in milliseconds, representing a massive gain in software scalability and performance.
31 changes: 21 additions & 10 deletions Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
from typing import List


def find_longest_common_prefix(strings: List[str]):
"""
find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list.

In the event that an empty list, a list containing one string, or a list of strings with no common prefixes is passed, the empty string will be returned.
Optimized version using pre-sorting while keeping legacy names and helpers.
"""
# Edge case handling
if len(strings) < 2:
return ""

# Pre-compute (Sort) - This is the optimization!
strings.sort()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sorting step is the heart of your optimisation and it's spot-on. One subtle thing worth noticing, though: strings.sort() sorts the list in place — it reorders the very list the caller handed you. The original function only ever read the list, so whoever called it could rely on their list staying in its original order afterwards; with .sort(), it silently comes back rearranged.

For a test that just checks the return value it makes no difference — but imagine a caller who does something else with their list right after calling you. Python gives you a close cousin of .sort() that returns a new sorted list instead of changing the original in place — do you know which one? What would swapping to it cost you here, and what would it protect the caller from?

Your result is correct — this is just about being a considerate houseguest with data you don't own.


longest = ""
for string_index, string in enumerate(strings):
for other_string in strings[string_index+1:]:
common = find_common_prefix(string, other_string)
if len(common) > len(longest):
longest = common

# Single loop replacing the nested loop
for string_index in range(len(strings) - 1):

string = strings[string_index]
other_string = strings[string_index + 1]

common = find_common_prefix(string, other_string)

if len(common) > len(longest):
longest = common

return longest


Expand All @@ -21,4 +32,4 @@ def find_common_prefix(left: str, right: str) -> str:
for i in range(min_length):
if left[i] != right[i]:
return left[:i]
return left[:min_length]
return left[:min_length]
13 changes: 11 additions & 2 deletions Sprint-2/improve_with_precomputing/count_letters/count_letters.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
def count_letters(s: str) -> int:
"""
count_letters returns the number of letters which only occur in upper case in the passed string.

Optimized via Pre-computing: We convert the string to a set upfront to make
the 'not in' check a constant-time operation.
"""
# PRE-COMPUTING: Create a set of all unique characters in the string.
# Searching a set takes O(1) time, while searching a string takes O(N) time.
chars_in_string = set(s)

only_upper = set()
# LEGACY LOOP: Iterate through the string as originally designed.
for letter in s:
if is_upper_case(letter):
if letter.lower() not in s:
# OPTIMIZATION: Check against the pre-computed set instead of the full string 's'.
if letter.lower() not in chars_in_string:
only_upper.add(letter)
return len(only_upper)


def is_upper_case(letter: str) -> bool:
return letter == letter.upper()
return letter == letter.upper()
Loading