Binary TreesBinary Trees36
  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Inorder Traversal of a Binary Tree using Recursion
  4. 4Inorder Traversal of a Binary Tree using Iteration
  5. 5Postorder Traversal of a Binary Tree Using Recursion
  6. 6Postorder Traversal of a Binary Tree using Iteration
  7. 7Level Order Traversal of a Binary Tree using Recursion
  8. 8Level Order Traversal of a Binary Tree using Iteration
  9. 9Reverse Level Order Traversal of a Binary Tree using Iteration
  10. 10Reverse Level Order Traversal of a Binary Tree using Recursion
  11. 11Find Height of a Binary Tree
  12. 12Find Diameter of a Binary Tree
  13. 13Find Mirror of a Binary Tree
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree
GraphsGraphs46
  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

Delete Word from Trie

Problem Statement

Given a set of words inserted into a Trie, implement a function to delete a specific word from it. Ensure the function properly handles edge cases such as shared prefixes or non-existent words. The function should not delete nodes that are part of other valid words.

Examples

Inserted Words Word to Delete Expected Trie Behavior Explanation
["apple", "banana", "grape"]
"banana" "banana" removed, others unchanged
"banana" is fully deleted, and since no other word shares its path, the whole branch is removed. Visualization
["car", "cart", "carbon"]
"car" "car" end marker removed, prefix retained
"car" shares prefix with "cart" and "carbon", so only the end-of-word marker is removed for "car". Visualization
["hello", "world"]
"hell" No change
"hell" was never inserted as a word, so nothing changes in the Trie. Visualization
[] "apple" No change The Trie is empty, so there's nothing to delete. Visualization

Visualization Player

Solution

Deleting a word from a Trie is a bit more complex than inserting or searching. This is because we must ensure that we only remove the nodes that are no longer required by other words. To do this, we use a recursive approach that checks whether a node is part of any other word before removing it.

Approach and Steps

We define a recursive function deleteWord(node, word, index) that traverses the Trie from the root node.

  1. If we reach the end of the word (i.e., index === word.length), we check if the word actually exists in the Trie.
  2. If it exists, we unset the is_end_of_word flag. If this node has no children, we tell the parent it can safely remove this node.
  3. As we return back up the recursive call stack, we check each node to see if its child (just deleted) can be removed, and if so, we remove it from the current node’s children.
  4. At each level, we check if the current node is still useful: it must either have children or be marked as an end of another word. If not, it can also be deleted.

Example: Deleting "ant" from a Trie

Let’s assume we have already inserted the words: ["app", "apple", "and", "ant", "danger", "dance"] into the Trie.

  1. We call deleteWord(root, "ant", 0).
  2. The function navigates through each character: 'a' → 'n' → 't'.
  3. At node 't', we unmark is_end_of_word = false.
  4. We check if 't' has any children — it doesn't, so it can be deleted from its parent 'n'.
  5. Next, we check 'n' — since it's still used by the word "and", we do not delete 'n'.
  6. The word "ant" is deleted, but the shared nodes needed by "and" are preserved.

Case 1 – Deleting a word that exists and has unique path

Example: Trie contains ["cat", "dog"], and we delete "dog".

  • Traversal goes 'd' → 'o' → 'g'.
  • 'g' is end of word and has no children → deleted.
  • 'o' now has no children → deleted.
  • 'd' now has no children → deleted.
  • The entire branch "dog" is removed from the Trie.

Case 2 – Deleting a word that is a prefix for another word

Example: Trie contains ["bat", "batch"], and we delete "bat".

  • Traversal reaches 't' and unmarks it as end of word.
  • 't' has a child ('c' from "batch") → node must not be deleted.
  • Only the is_end_of_word flag is updated, structure remains.

Case 3 – Trying to delete a word that does not exist

Example: Trie contains ["cat", "car"], and we try to delete "can".

  • Traversal fails at node 'n', which doesn't exist under 'a'.
  • Function returns false, and Trie remains unchanged.

Case 4 – Deleting a word from an empty Trie

Example: Trie is empty, and we try to delete the word "apple".

  • Since the root has no children, traversal stops immediately.
  • Return false, no changes made.

Case 5 – Deleting the only word in the Trie

Example: Trie contains ["run"], and we delete "run".

  • Each node is unmarked and deleted from leaf to root.
  • After deletion, the Trie becomes empty again.

Algorithm Steps

  1. Start from the root node and define a recursive function deleteWord(node, word, index).
  2. If index equals the word's length:
    1. If node.is_end_of_word is false, the word does not exist — return false.
    2. Unset node.is_end_of_word.
    3. Return true if node.children is empty (to delete this node in parent).
  3. Get the current character and its corresponding child node.
  4. If the child node does not exist, return false.
  5. Recursively call deleteWord on the child node and next index.
  6. After recursion, if deletion is needed, remove the child from current node's children map.
  7. Return true if the current node is not end of another word and has no children left.

Code

Python
Java
JavaScript
C
C++
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end_of_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end_of_word = True

    def search(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.is_end_of_word

    def delete(self, word):
        def _delete(node, word, index):
            if index == len(word):
                if not node.is_end_of_word:
                    return False
                node.is_end_of_word = False
                return len(node.children) == 0
            char = word[index]
            if char not in node.children:
                return False
            should_delete = _delete(node.children[char], word, index + 1)
            if should_delete:
                del node.children[char]
                return not node.is_end_of_word and len(node.children) == 0
            return False
        _delete(self.root, word, 0)

# Example
trie = Trie()
trie.insert("apple")
trie.insert("app")
trie.delete("apple")
print(trie.search("apple"))  # False
print(trie.search("app"))    # True

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)In the best case, the algorithm still traverses each character of the word once, resulting in linear time complexity relative to the word length.
Average CaseO(n)On average, the algorithm traverses n nodes (one for each character of the word) and performs constant-time operations at each node, leading to O(n) time.
Worst CaseO(n)In the worst case, the algorithm traverses down the full length of the word and may also backtrack up to remove unnecessary nodes, still bounded by O(n).

Space Complexity

O(n)

Explanation: The space complexity is O(n) due to the recursion stack, which can go as deep as the length of the word being deleted.