Skip to content

Commit 9c67d24

Browse files
authored
Merge pull request #1569 from ivanpenaloza/march07
adding algo
2 parents 95e9fb8 + 9f8056d commit 9c67d24

5 files changed

Lines changed: 238 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def twoSum(self, nums: List[int], target: int) -> List[int]:
6+
7+
answer = dict()
8+
9+
for k, v in enumerate(nums):
10+
11+
if v in answer:
12+
return [answer[v], k]
13+
else:
14+
answer[target - v] = k
15+
16+
return []
17+
18+
19+
20+
21+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
import re
4+
5+
class Solution:
6+
def isPalindrome(self, s: str) -> bool:
7+
8+
# To lowercase
9+
s = s.lower()
10+
11+
# Remove non-alphanumeric characters
12+
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)
13+
14+
# Determine if s is palindrome or not
15+
len_s = len(s)
16+
17+
for i in range(len_s//2):
18+
19+
if s[i] != s[len_s - 1 - i]:
20+
return False
21+
22+
return True
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
from collections import deque, defaultdict
4+
5+
class TrieNode:
6+
def __init__(self):
7+
self.children = {}
8+
self.word = None # Store the complete word at the end node
9+
10+
class Solution:
11+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
12+
# Build Trie from words
13+
root = TrieNode()
14+
for word in words:
15+
node = root
16+
for char in word:
17+
if char not in node.children:
18+
node.children[char] = TrieNode()
19+
node = node.children[char]
20+
node.word = word
21+
22+
m, n = len(board), len(board[0])
23+
result = []
24+
25+
def dfs(i, j, node):
26+
# Get current character
27+
char = board[i][j]
28+
29+
# Check if character exists in Trie
30+
if char not in node.children:
31+
return
32+
33+
next_node = node.children[char]
34+
35+
# If we found a word, add it to result
36+
if next_node.word:
37+
result.append(next_node.word)
38+
next_node.word = None # Avoid duplicate results
39+
40+
# Mark cell as visited
41+
board[i][j] = '#'
42+
43+
# Explore all 4 directions
44+
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
45+
ni, nj = i + di, j + dj
46+
if 0 <= ni < m and 0 <= nj < n and board[ni][nj] != '#':
47+
dfs(ni, nj, next_node)
48+
49+
# Restore cell
50+
board[i][j] = char
51+
52+
# Optimization: remove leaf nodes to prune the Trie
53+
if not next_node.children:
54+
del node.children[char]
55+
56+
# Start DFS from each cell
57+
for i in range(m):
58+
for j in range(n):
59+
dfs(i, j, root)
60+
61+
return result
62+
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class TrieNode {
2+
children: Map<string, TrieNode>;
3+
word: string | null;
4+
5+
constructor() {
6+
this.children = new Map();
7+
this.word = null; // Store the complete word at the end node
8+
}
9+
}
10+
11+
function findWords(board: string[][], words: string[]): string[] {
12+
// Build Trie from words
13+
const root = new TrieNode();
14+
for (const word of words) {
15+
let node = root;
16+
for (const char of word) {
17+
if (!node.children.has(char)) {
18+
node.children.set(char, new TrieNode());
19+
}
20+
node = node.children.get(char)!;
21+
}
22+
node.word = word;
23+
}
24+
25+
const m = board.length;
26+
const n = board[0].length;
27+
const result: string[] = [];
28+
29+
function dfs(i: number, j: number, node: TrieNode): void {
30+
// Get current character
31+
const char = board[i][j];
32+
33+
// Check if character exists in Trie
34+
if (!node.children.has(char)) {
35+
return;
36+
}
37+
38+
const nextNode = node.children.get(char)!;
39+
40+
// If we found a word, add it to result
41+
if (nextNode.word !== null) {
42+
result.push(nextNode.word);
43+
nextNode.word = null; // Avoid duplicate results
44+
}
45+
46+
// Mark cell as visited
47+
board[i][j] = '#';
48+
49+
// Explore all 4 directions
50+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
51+
for (const [di, dj] of directions) {
52+
const ni = i + di;
53+
const nj = j + dj;
54+
if (ni >= 0 && ni < m && nj >= 0 && nj < n && board[ni][nj] !== '#') {
55+
dfs(ni, nj, nextNode);
56+
}
57+
}
58+
59+
// Restore cell
60+
board[i][j] = char;
61+
62+
// Optimization: remove leaf nodes to prune the Trie
63+
if (nextNode.children.size === 0) {
64+
node.children.delete(char);
65+
}
66+
}
67+
68+
// Start DFS from each cell
69+
for (let i = 0; i < m; i++) {
70+
for (let j = 0; j < n; j++) {
71+
dfs(i, j, root);
72+
}
73+
}
74+
75+
return result;
76+
}
77+
78+
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import unittest
2+
from typing import Optional, List
3+
from src.my_project.interviews.top_150_questions_round_22\
4+
.ex_95_word_search_ii import Solution
5+
6+
7+
class WordSearchIITestCase(unittest.TestCase):
8+
9+
def test_example_1(self):
10+
"""
11+
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]],
12+
words = ["oath","pea","eat","rain"]
13+
Output: ["eat","oath"]
14+
"""
15+
solution = Solution()
16+
board = [
17+
["o", "a", "a", "n"],
18+
["e", "t", "a", "e"],
19+
["i", "h", "k", "r"],
20+
["i", "f", "l", "v"]
21+
]
22+
words = ["oath", "pea", "eat", "rain"]
23+
result = solution.findWords(board, words)
24+
self.assertEqual(sorted(result), sorted(["eat", "oath"]))
25+
26+
def test_example_2(self):
27+
"""
28+
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
29+
Output: []
30+
"""
31+
solution = Solution()
32+
board = [["a", "b"], ["c", "d"]]
33+
words = ["abcb"]
34+
result = solution.findWords(board, words)
35+
self.assertEqual(result, [])
36+
37+
def test_single_cell(self):
38+
"""
39+
Test with single cell board
40+
"""
41+
solution = Solution()
42+
board = [["a"]]
43+
words = ["a", "b"]
44+
result = solution.findWords(board, words)
45+
self.assertEqual(result, ["a"])
46+
47+
def test_no_words_found(self):
48+
"""
49+
Test when no words are found
50+
"""
51+
solution = Solution()
52+
board = [["a", "b"], ["c", "d"]]
53+
words = ["xyz", "pqr"]
54+
result = solution.findWords(board, words)
55+
self.assertEqual(result, [])

0 commit comments

Comments
 (0)