Skip to content

feat/(lgorithms, backtracking dfs trie): word search#130

Merged
BrianLusina merged 3 commits intomainfrom
feat/algorithms-backtracking-dfs-trie-word-search
Dec 27, 2025
Merged

feat/(lgorithms, backtracking dfs trie): word search#130
BrianLusina merged 3 commits intomainfrom
feat/algorithms-backtracking-dfs-trie-word-search

Conversation

@BrianLusina
Copy link
Copy Markdown
Owner

@BrianLusina BrianLusina commented Dec 26, 2025

Describe your change:

Word search

  • 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

  • New Features

    • Word Search: find single words in grids across all directions.
    • Word Search 2: find multiple words in grids using backtracking.
    • Dictionary structure can now remove stored words.
  • Documentation

    • Added detailed guides for both Word Search problems with examples and complexity notes; removed legacy Word Search docs.
  • Tests

    • Added and updated tests covering the new word search functionality.

✏️ Tip: You can customize this high-level summary in your review settings.

@BrianLusina BrianLusina self-assigned this Dec 26, 2025
@BrianLusina BrianLusina added enhancement Algorithm Algorithm Problem Datastructures Datastructures Documentation Documentation Updates Backtracking Backtracking Algorithm Array Array data structure Trees Trie labels Dec 26, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 26, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This PR moves Word Search from algorithms/word_search/ into algorithms/backtracking/word_search/, splits the implementation into Point, constants, and core modules, adds a find_strings trie-based solver, new tests and docs, and adds a Trie.remove_characters method. Deleted the old monolithic module and README.

Changes

Cohort / File(s) Summary
Removed legacy Word Search
algorithms/word_search/__init__.py, algorithms/word_search/README.md
Deleted the original monolithic WordSearch module and its README.
Backtracking Word Search implementation
algorithms/backtracking/word_search/__init__.py
Added WordSearch class (grid parsing, search/find_word/find_char) and added find_strings(grid, words) implementing DFS + Trie for multi-word search.
Point & Direction constants
algorithms/backtracking/word_search/point.py, algorithms/backtracking/word_search/constants.py
New Point class (coords, arithmetic, equality) and PLANE_LIMITS directional offsets.
Documentation
algorithms/backtracking/word_search/README.md, DIRECTORY.md
New README for backtracking word-search variants; updated DIRECTORY.md to reflect relocated entries and new Word Count entries.
Tests
algorithms/backtracking/word_search/test_word_search.py, algorithms/backtracking/word_search/test_word_search_two.py
Updated imports to new paths; added parameterized tests for find_strings (Word Search 2).
Trie enhancement
datastructures/trees/trie/trie.py
Added remove_characters(self, string_to_delete: str) to prune deleted words from the Trie during search.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Test as Test Runner
  participant Finder as find_strings
  participant Grid as Grid (2D array)
  participant Trie as Trie

  Note over Test,Finder: Start multi-word search
  Test->>Finder: find_strings(grid, words)
  Finder->>Trie: build trie(words)
  Finder->>Grid: iterate cells (i,j)
  alt cell starts a trie path
    Finder->>Trie: prefix lookup (char)
    Finder->>Grid: DFS explore neighbors (up/down/left/right)
    Grid->>Finder: char at coordinate
    Finder->>Trie: advance node
    alt word found
      Finder->>Trie: mark found, call remove_characters(word)
      Finder->>Finder: record word in results
    end
  end
  Finder-->>Test: return found words list
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped through grids of lettered gleams,

Traced paths and pruned the trie of dreams,
Points and planes now split and play,
Words found, tests pass, I munch away!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 2 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.25% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title has a typo and is unclear; '/(lgorithms' appears to be a malformed placeholder, making the title ambiguous about the core change despite mentioning word search. Correct the title to something like 'feat(algorithms, backtracking): add word search implementations' to clearly describe the main change without typos or unclear notation.
Description check ❓ Inconclusive The description follows the template structure but lacks detail; 'Word search' is vague and doesn't explain what specifically was added, the issues addressed, or the implementation approach. Expand the description to explain what word search implementations were added (e.g., single word search and finding multiple words using trie), why changes were made, and any important implementation details.

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5fb290f and 406abff.

📒 Files selected for processing (1)
  • algorithms/backtracking/word_search/__init__.py

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: 4

🧹 Nitpick comments (5)
datastructures/trees/trie/trie.py (1)

88-106: Missing return type annotation and potential KeyError if string doesn't exist.

The method lacks a return type annotation and will raise KeyError if string_to_delete doesn't exist in the trie. While current usage in find_strings ensures the path exists, defensive coding would improve robustness.

🔎 Proposed improvements
-    def remove_characters(self, string_to_delete: str):
+    def remove_characters(self, string_to_delete: str) -> None:
         """
         Removes a string from the trie
         """
         node = self.root
         child_list = []
 
         for c in string_to_delete:
+            if c not in node.children:
+                return  # String not in trie, nothing to remove
-            child_list.append([node, c])
+            child_list.append((node, c))
             node = node.children[c]
 
         for pair in reversed(child_list):
             parent = pair[0]
             child_char = pair[1]
             target = parent.children[child_char]
 
             if target.children:
                 return
             del parent.children[child_char]
algorithms/backtracking/word_search/README.md (1)

9-20: Missing language specifier for fenced code block.

The code block at line 9 should have a language specifier for proper syntax highlighting.

🔎 Proposed fix
-```
+```text
 jefblpepre
 camdcimgtc
 oivokprjsm
 pbwasqroua
 rixilelhrs
 wolcqlirpc
 screeaumgr
 alxhpburyi
 jalaycalmp
 clojurermt
</details>

</blockquote></details>
<details>
<summary>algorithms/backtracking/word_search/point.py (2)</summary><blockquote>

`7-14`: **Consider adding type hints for constructor parameters.**

The `Point` class would benefit from type annotations for consistency with the rest of the codebase.


<details>
<summary>🔎 Proposed improvement</summary>

```diff
-    def __init__(self, x, y):
+    def __init__(self, x: int, y: int) -> None:
         """
         Creates a new cartesian point object
         :param x: point on x-axis
         :param y: point on y-axis
         """
         self.x = x
         self.y = y

16-17: Non-standard __repr__ format uses colon separator.

The __repr__ uses Point(x:y) format instead of the conventional Point(x, y). This doesn't affect functionality but could be confusing since it doesn't match the constructor signature.

🔎 Proposed fix
     def __repr__(self):
-        return "Point({}:{})".format(self.x, self.y)
+        return f"Point({self.x}, {self.y})"
algorithms/backtracking/word_search/__init__.py (1)

92-93: Consider using a named function instead of lambda assignment.

Assigning a lambda to a variable is discouraged by PEP 8 (E731). A named function provides better debugging and documentation.

🔎 Proposed refactor
-    # lambda function to check if the current cell is within the grid
-    is_cell_within_grid = lambda r, c: 0 <= r < rows_count and 0 <= c < cols_count
+    def is_cell_within_grid(r: int, c: int) -> bool:
+        """Check if the current cell is within the grid."""
+        return 0 <= r < rows_count and 0 <= c < cols_count
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa7a075 and 5fb290f.

⛔ Files ignored due to path filters (5)
  • algorithms/backtracking/word_search/images/examples/word_search_two_example_1.png is excluded by !**/*.png
  • algorithms/backtracking/word_search/images/examples/word_search_two_example_2.png is excluded by !**/*.png
  • algorithms/backtracking/word_search/images/examples/word_search_two_example_3.png is excluded by !**/*.png
  • algorithms/backtracking/word_search/images/examples/word_search_two_example_4.png is excluded by !**/*.png
  • algorithms/backtracking/word_search/images/examples/word_search_two_example_5.png is excluded by !**/*.png
📒 Files selected for processing (11)
  • DIRECTORY.md
  • algorithms/backtracking/word_search/README.md
  • algorithms/backtracking/word_search/__init__.py
  • algorithms/backtracking/word_search/constants.py
  • algorithms/backtracking/word_search/point.py
  • algorithms/backtracking/word_search/test_word_search.py
  • algorithms/backtracking/word_search/test_word_search_two.py
  • algorithms/word_count/test_word_count.py
  • algorithms/word_search/README.md
  • algorithms/word_search/__init__.py
  • datastructures/trees/trie/trie.py
💤 Files with no reviewable changes (2)
  • algorithms/word_search/README.md
  • algorithms/word_search/init.py
🧰 Additional context used
🧬 Code graph analysis (4)
algorithms/backtracking/word_search/__init__.py (2)
algorithms/backtracking/word_search/point.py (1)
  • Point (1-29)
datastructures/trees/trie/trie.py (5)
  • Trie (5-109)
  • search (51-73)
  • insert (9-49)
  • dfs (65-70)
  • remove_characters (88-106)
algorithms/backtracking/word_search/test_word_search_two.py (1)
algorithms/backtracking/word_search/__init__.py (1)
  • find_strings (71-147)
algorithms/backtracking/word_search/test_word_search.py (2)
algorithms/backtracking/word_search/point.py (1)
  • Point (1-29)
algorithms/backtracking/word_search/__init__.py (1)
  • WordSearch (8-68)
algorithms/backtracking/word_search/constants.py (1)
algorithms/backtracking/word_search/point.py (1)
  • Point (1-29)
🪛 LanguageTool
algorithms/backtracking/word_search/README.md

[grammar] ~32-~32: Ensure spelling is correct
Context: ...this word. It must return the Points of thw first and last letter of the word if fo...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[grammar] ~54-~54: Ensure spelling is correct
Context: ...d the last letter e can be found at poin 6, 9 > Note: indexes start counting fro...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[style] ~77-~77: To elevate your writing, try using an alternative expression here.
Context: ... The order of the strings in the output does not matter. ## Examples ![Example 1](images/exam...

(MATTERS_RELEVANT)

🪛 markdownlint-cli2 (0.18.1)
DIRECTORY.md

41-41: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


42-42: Unordered list indentation
Expected: 4; Actual: 6

(MD007, ul-indent)


43-43: Unordered list indentation
Expected: 4; Actual: 6

(MD007, ul-indent)


44-44: Unordered list indentation
Expected: 4; Actual: 6

(MD007, ul-indent)


45-45: Unordered list indentation
Expected: 4; Actual: 6

(MD007, ul-indent)


182-182: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


183-183: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

algorithms/backtracking/word_search/README.md

9-9: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


73-73: Reference links and images should use a label that is defined
Missing link or image reference definition: "j"

(MD052, reference-links-images)


105-105: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)

🔇 Additional comments (5)
algorithms/backtracking/word_search/test_word_search.py (1)

2-3: LGTM!

The import paths are correctly updated to reflect the module relocation to algorithms/backtracking/word_search. The test coverage for various word search directions (horizontal, vertical, diagonal, and edge cases) is comprehensive.

DIRECTORY.md (1)

41-45: LGTM!

The new Word Search entries under the Backtracking section correctly document the relocated and newly added files (constants.py, point.py, and test files). The structure matches the existing documentation format.

algorithms/backtracking/word_search/constants.py (1)

1-13: LGTM!

The PLANE_LIMITS constant correctly defines all eight directional offsets (cardinal and diagonal) for grid traversal. Using an immutable tuple is appropriate for a constant, and the Point objects provide consistent vector arithmetic throughout the word search implementation.

algorithms/backtracking/word_search/test_word_search_two.py (1)

64-70: LGTM! Good use of parameterized testing.

The test structure is clean with comprehensive test cases covering various grid configurations. Consider adding edge case tests for empty grids or empty word lists in a future iteration.

algorithms/backtracking/word_search/__init__.py (1)

71-147: Well-implemented Word Search 2 algorithm using Trie with DFS backtracking.

The implementation correctly:

  • Builds a Trie from input words for efficient prefix matching
  • Uses DFS with backtracking to explore all paths
  • Prevents duplicates by clearing is_end after finding a word
  • Prunes the Trie to optimize future searches
  • Properly manages the visited set for backtracking

The algorithm aligns with the documented O(n*3^l) time complexity.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@BrianLusina BrianLusina merged commit 4aff926 into main Dec 27, 2025
4 of 7 checks passed
@BrianLusina BrianLusina deleted the feat/algorithms-backtracking-dfs-trie-word-search branch December 27, 2025 03:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Algorithm Algorithm Problem Array Array data structure Backtracking Backtracking Algorithm Datastructures Datastructures Documentation Documentation Updates enhancement Trees Trie

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant