Skip to content

feat(datastructures): map sum pairs#189

Merged
BrianLusina merged 2 commits intomainfrom
feat/datastructures-map-sum
Mar 18, 2026
Merged

feat(datastructures): map sum pairs#189
BrianLusina merged 2 commits intomainfrom
feat/datastructures-map-sum

Conversation

@BrianLusina
Copy link
Copy Markdown
Owner

@BrianLusina BrianLusina commented Mar 18, 2026

Describe your change:

Map Sum Pairs data structure

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
  • If this pull request resolves one or more open issues then the commit message contains Fixes: #{$ISSUE_NO}.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced Map Sum Pairs data structure supporting insert and prefix-sum operations.
  • Documentation

    • Added comprehensive Map Sum Pairs design documentation.
    • Expanded catalogue with new test entries across multiple sections.
  • Tests

    • Added parameterised tests for Map Sum implementations.
    • Extended word dictionary test coverage with additional scenarios.

@BrianLusina BrianLusina self-assigned this Mar 18, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 18, 2026

📝 Walkthrough

Walkthrough

This PR introduces a new MapSum data structure with three alternative implementations (brute-force, prefix-counter, and trie-based) alongside comprehensive tests and documentation. It extends the trie functionality by adding a score attribute to TrieNode and expands existing test coverage whilst updating the directory catalogue.

Changes

Cohort / File(s) Summary
MapSum Implementation
datastructures/map_sum/__init__.py, datastructures/map_sum/README.md
Introduces MapSum data structure with three implementations: brute-force dictionary scan, prefix-counter optimisation, and trie-based approach. Each variant exposes identical insert(key, val) and sum(prefix) interfaces with different performance characteristics.
MapSum Tests
datastructures/map_sum/test_map_sum_pairs.py
Adds parameterised test suite covering all three MapSum implementations with shared test cases validating insert and sum operations across multiple scenarios.
Trie Enhancements
datastructures/trees/trie/trie_node.py, datastructures/trees/trie/word_dictionary/test_word_dictionary.py
Extends TrieNode with a score attribute for use in prefix-sum calculations; expands WordDictionary test coverage with additional test case for word addition and pattern-based searching.
Directory Catalogue Updates
DIRECTORY.md
Adds nine new entries across multiple sections documenting MapSum Pairs, Construct Target With Sums, Append Chars To Make Subsequence, and Last Day Where You Can Still Cross implementations and their corresponding tests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A trie of three, now summing prefixes with grace,
Brute force meets counter, each one in its place,
With nodes that now score and tests that expand,
Our algorithms hop forward across the land!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main addition: a Map Sum Pairs data structure implementation.
Description check ✅ Passed The description covers the main change (Map Sum Pairs data structure), follows the template structure, and all critical checklist items are marked as complete.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/datastructures-map-sum
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
datastructures/map_sum/test_map_sum_pairs.py (1)

60-107: Reduce duplicated operation-runner logic across the three tests.

Line 60-Line 107 repeats the same execution/assertion loop three times. Extracting a shared helper keeps these tests easier to maintain.

♻️ Suggested refactor
 class MapSumPairsTestCase(unittest.TestCase):
+    def _assert_operations(self, map_sum, operations: List[Tuple[str, Tuple[str, int]]]) -> None:
+        for cmd, params in operations:
+            if cmd == "insert":
+                key, value = params
+                map_sum.insert(key, value)
+            if cmd == "sum":
+                prefix, expected = params
+                actual = map_sum.sum(prefix)
+                self.assertEqual(expected, actual)
+
     `@parameterized.expand`(MAP_SUM_TEST_CASES)
     def test_map_sum_pairs_brute_force(
         self, operations: List[Tuple[str, Tuple[str, int]]]
     ):
-        map_sum = MapSumBruteForce()
-        for operation in operations:
-            cmd = operation[0]
-            params = operation[1]
-            if cmd == "insert":
-                key, value = params
-                map_sum.insert(key, value)
-
-            if cmd == "sum":
-                prefix, expected = params
-                actual = map_sum.sum(prefix)
-                self.assertEqual(expected, actual)
+        self._assert_operations(MapSumBruteForce(), operations)

     `@parameterized.expand`(MAP_SUM_TEST_CASES)
     def test_map_sum_pairs_prefix(self, operations: List[Tuple[str, Tuple[str, int]]]):
-        map_sum = MapSumPrefix()
-        for operation in operations:
-            cmd = operation[0]
-            params = operation[1]
-            if cmd == "insert":
-                key, value = params
-                map_sum.insert(key, value)
-
-            if cmd == "sum":
-                prefix, expected = params
-                actual = map_sum.sum(prefix)
-                self.assertEqual(expected, actual)
+        self._assert_operations(MapSumPrefix(), operations)

     `@parameterized.expand`(MAP_SUM_TEST_CASES)
     def test_map_sum_pairs_trie(self, operations: List[Tuple[str, Tuple[str, int]]]):
-        map_sum = MapSumTrie()
-        for operation in operations:
-            cmd = operation[0]
-            params = operation[1]
-            if cmd == "insert":
-                key, value = params
-                map_sum.insert(key, value)
-
-            if cmd == "sum":
-                prefix, expected = params
-                actual = map_sum.sum(prefix)
-                self.assertEqual(expected, actual)
+        self._assert_operations(MapSumTrie(), operations)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@datastructures/map_sum/test_map_sum_pairs.py` around lines 60 - 107, Extract
the duplicated operation-runner loop into a helper method on MapSumPairsTestCase
(e.g., add a private method run_operations(self, map_sum, operations)) that
iterates operations, calls insert or sum on the provided map_sum instance and
performs the assertEqual checks; then simplify test_map_sum_pairs_brute_force,
test_map_sum_pairs_prefix, and test_map_sum_pairs_trie to construct their
MapSumBruteForce / MapSumPrefix / MapSumTrie instances and call
self.run_operations(map_sum, operations) instead of repeating the loop.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@datastructures/map_sum/README.md`:
- Around line 15-17: Update the API method signatures in the README to
Python-style for the MapSum methods: replace the Java-style lines for `insert`
and `sum` with Python signatures such as `def insert(self, key: str, val: int)
-> None` and `def sum(self, prefix: str) -> int` (or equivalent PEP484 type
hints used elsewhere), ensuring the method names `insert` and `sum` match the
implemented class (MapSum) and keep the descriptions unchanged.

In `@datastructures/trees/trie/trie_node.py`:
- Around line 10-11: The TrieNode docstring incorrectly states the node
"contains a character"; update the docstring for class TrieNode to describe the
actual attributes: children (dict mapping chars to TrieNode), is_end (bool),
index (optional/int), and score (optional/float), and remove the mention of a
stored character so the description matches the implemented fields (refer to
TrieNode, children, is_end, index, score).

---

Nitpick comments:
In `@datastructures/map_sum/test_map_sum_pairs.py`:
- Around line 60-107: Extract the duplicated operation-runner loop into a helper
method on MapSumPairsTestCase (e.g., add a private method run_operations(self,
map_sum, operations)) that iterates operations, calls insert or sum on the
provided map_sum instance and performs the assertEqual checks; then simplify
test_map_sum_pairs_brute_force, test_map_sum_pairs_prefix, and
test_map_sum_pairs_trie to construct their MapSumBruteForce / MapSumPrefix /
MapSumTrie instances and call self.run_operations(map_sum, operations) instead
of repeating the loop.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fdeeca73-0ec4-410a-abec-0929f68c2dca

📥 Commits

Reviewing files that changed from the base of the PR and between 1791c05 and 2520ddd.

⛔ Files ignored due to path filters (3)
  • datastructures/map_sum/images/examples/map_sum_pairs_example_1.png is excluded by !**/*.png
  • datastructures/map_sum/images/examples/map_sum_pairs_example_2.png is excluded by !**/*.png
  • datastructures/map_sum/images/examples/map_sum_pairs_example_3.png is excluded by !**/*.png
📒 Files selected for processing (6)
  • DIRECTORY.md
  • datastructures/map_sum/README.md
  • datastructures/map_sum/__init__.py
  • datastructures/map_sum/test_map_sum_pairs.py
  • datastructures/trees/trie/trie_node.py
  • datastructures/trees/trie/word_dictionary/test_word_dictionary.py

@BrianLusina BrianLusina merged commit 79b7801 into main Mar 18, 2026
5 of 6 checks passed
@BrianLusina BrianLusina deleted the feat/datastructures-map-sum branch March 23, 2026 06:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant