Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

answer = dict()

for k, v in enumerate(nums):

if v in answer:
return [answer[v], k]
else:
answer[target - v] = k

return []





Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
import re

class Solution:
def isPalindrome(self, s: str) -> bool:

# To lowercase
s = s.lower()

# Remove non-alphanumeric characters
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)

# Determine if s is palindrome or not
len_s = len(s)

for i in range(len_s//2):

if s[i] != s[len_s - 1 - i]:
return False

return True
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
from collections import deque, defaultdict

class TrieNode:
def __init__(self):
self.children = {}
self.word = None # Store the complete word at the end node

class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# Build Trie from words
root = TrieNode()
for word in words:
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.word = word

m, n = len(board), len(board[0])
result = []

def dfs(i, j, node):
# Get current character
char = board[i][j]

# Check if character exists in Trie
if char not in node.children:
return

next_node = node.children[char]

# If we found a word, add it to result
if next_node.word:
result.append(next_node.word)
next_node.word = None # Avoid duplicate results

# Mark cell as visited
board[i][j] = '#'

# Explore all 4 directions
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and board[ni][nj] != '#':
dfs(ni, nj, next_node)

# Restore cell
board[i][j] = char

# Optimization: remove leaf nodes to prune the Trie
if not next_node.children:
del node.children[char]

# Start DFS from each cell
for i in range(m):
for j in range(n):
dfs(i, j, root)

return result

Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
class TrieNode {
children: Map<string, TrieNode>;
word: string | null;

constructor() {
this.children = new Map();
this.word = null; // Store the complete word at the end node
}
}

function findWords(board: string[][], words: string[]): string[] {
// Build Trie from words
const root = new TrieNode();
for (const word of words) {
let node = root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.word = word;
}

const m = board.length;
const n = board[0].length;
const result: string[] = [];

function dfs(i: number, j: number, node: TrieNode): void {
// Get current character
const char = board[i][j];

// Check if character exists in Trie
if (!node.children.has(char)) {
return;
}

const nextNode = node.children.get(char)!;

// If we found a word, add it to result
if (nextNode.word !== null) {
result.push(nextNode.word);
nextNode.word = null; // Avoid duplicate results
}

// Mark cell as visited
board[i][j] = '#';

// Explore all 4 directions
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
for (const [di, dj] of directions) {
const ni = i + di;
const nj = j + dj;
if (ni >= 0 && ni < m && nj >= 0 && nj < n && board[ni][nj] !== '#') {
dfs(ni, nj, nextNode);
}
}

// Restore cell
board[i][j] = char;

// Optimization: remove leaf nodes to prune the Trie
if (nextNode.children.size === 0) {
node.children.delete(char);
}
}

// Start DFS from each cell
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
dfs(i, j, root);
}
}

return result;
}


55 changes: 55 additions & 0 deletions tests/test_150_questions_round_22/test_95_word_search_ii_round.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import unittest
from typing import Optional, List
from src.my_project.interviews.top_150_questions_round_22\
.ex_95_word_search_ii import Solution


class WordSearchIITestCase(unittest.TestCase):

def test_example_1(self):
"""
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]],
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
"""
solution = Solution()
board = [
["o", "a", "a", "n"],
["e", "t", "a", "e"],
["i", "h", "k", "r"],
["i", "f", "l", "v"]
]
words = ["oath", "pea", "eat", "rain"]
result = solution.findWords(board, words)
self.assertEqual(sorted(result), sorted(["eat", "oath"]))

def test_example_2(self):
"""
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
"""
solution = Solution()
board = [["a", "b"], ["c", "d"]]
words = ["abcb"]
result = solution.findWords(board, words)
self.assertEqual(result, [])

def test_single_cell(self):
"""
Test with single cell board
"""
solution = Solution()
board = [["a"]]
words = ["a", "b"]
result = solution.findWords(board, words)
self.assertEqual(result, ["a"])

def test_no_words_found(self):
"""
Test when no words are found
"""
solution = Solution()
board = [["a", "b"], ["c", "d"]]
words = ["xyz", "pqr"]
result = solution.findWords(board, words)
self.assertEqual(result, [])