From c8b0c592164c10a837e75bad181024024028a3e0 Mon Sep 17 00:00:00 2001 From: iswat Date: Wed, 1 Jul 2026 18:36:53 +0100 Subject: [PATCH 1/3] perf: optimize longest common prefix search via pre-sorting - Implement alphabetical sorting to bring strings with common prefixes together - Replace the nested O(N^2) loop with a single pass over neighboring strings - Maintain legacy variable names and the 'find_common_prefix' helper function - Add early return for lists with fewer than two strings --- .../common_prefix/common_prefix.py | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py b/Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py index f4839e7..f2b8f3e 100644 --- a/Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py +++ b/Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py @@ -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() + 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 @@ -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] \ No newline at end of file From a35d066bf2cbf8a1ff669e8a5f528281deca6221 Mon Sep 17 00:00:00 2001 From: iswat Date: Wed, 1 Jul 2026 18:52:54 +0100 Subject: [PATCH 2/3] perf: optimize count_letters via pre-computed character set - Replace O(N) string scanning with O(1) set lookup - Transition overall algorithm complexity from O(N^2) to O(N) - Maintain legacy loop structure and helper functions for minimal code changes - Add documentation explaining the pre-computing strategy --- .../count_letters/count_letters.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Sprint-2/improve_with_precomputing/count_letters/count_letters.py b/Sprint-2/improve_with_precomputing/count_letters/count_letters.py index 62c3ec0..37974ab 100644 --- a/Sprint-2/improve_with_precomputing/count_letters/count_letters.py +++ b/Sprint-2/improve_with_precomputing/count_letters/count_letters.py @@ -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() \ No newline at end of file From e14f31ba09d23473fe7b1af29ab6a558fea93f99 Mon Sep 17 00:00:00 2001 From: iswat Date: Wed, 1 Jul 2026 18:57:57 +0100 Subject: [PATCH 3/3] docs: document pre-computing optimizations - Explain the O(N^2) to O(N log N) improvement via pre-sorting in common_prefix - Detail the O(N^2) to O(N) transition using set lookups in count_letters - Summarize the Space-vs-Time trade-offs applied to both algorithms - Note the preservation of legacy variable names and helper functions --- .../improve_with_precomputing/CHANGES_MADE.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Sprint-2/improve_with_precomputing/CHANGES_MADE.md diff --git a/Sprint-2/improve_with_precomputing/CHANGES_MADE.md b/Sprint-2/improve_with_precomputing/CHANGES_MADE.md new file mode 100644 index 0000000..e926ffd --- /dev/null +++ b/Sprint-2/improve_with_precomputing/CHANGES_MADE.md @@ -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. \ No newline at end of file