Skip to content

Commit 0c5fda8

Browse files
authored
Merge pull request #1563 from ivanpenaloza/march01
adding algo
2 parents 624dec9 + 5bb686b commit 0c5fda8

5 files changed

Lines changed: 242 additions & 0 deletions

File tree

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+
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+
22+
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: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
from collections import deque, defaultdict
4+
5+
class Solution:
6+
def snakesAndLadders(self, board: List[List[int]]) -> int:
7+
n = len(board)
8+
9+
# Helper function to convert square number to (row, col) coordinates
10+
def get_position(square):
11+
# square is 1-indexed, convert to 0-indexed
12+
square -= 1
13+
# Calculate row from bottom (0 is bottom row)
14+
row = square // n
15+
# Calculate column based on row direction
16+
if row % 2 == 0:
17+
# Even rows (from bottom): left to right
18+
col = square % n
19+
else:
20+
# Odd rows (from bottom): right to left
21+
col = n - 1 - (square % n)
22+
# Convert to board coordinates (0 is top row in board)
23+
return n - 1 - row, col
24+
25+
# BFS to find shortest path
26+
target = n * n
27+
queue = deque([(1, 0)]) # (current_square, num_moves)
28+
visited = {1}
29+
30+
while queue:
31+
curr, moves = queue.popleft()
32+
33+
# Try all possible dice rolls (1 to 6)
34+
for dice in range(1, 7):
35+
next_square = curr + dice
36+
37+
# Check if we've gone beyond the board
38+
if next_square > target:
39+
break
40+
41+
# Get the board position for this square
42+
r, c = get_position(next_square)
43+
44+
# Check if there's a snake or ladder
45+
if board[r][c] != -1:
46+
next_square = board[r][c]
47+
48+
# Check if we've reached the target
49+
if next_square == target:
50+
return moves + 1
51+
52+
# Add to queue if not visited
53+
if next_square not in visited:
54+
visited.add(next_square)
55+
queue.append((next_square, moves + 1))
56+
57+
# If we can't reach the target
58+
return -1
59+
60+
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
function snakesAndLadders(board: number[][]): number {
2+
const n = board.length;
3+
4+
// Helper function to convert square number to (row, col) coordinates
5+
function getPosition(square: number): [number, number] {
6+
// square is 1-indexed, convert to 0-indexed
7+
square -= 1;
8+
// Calculate row from bottom (0 is bottom row)
9+
const row = Math.floor(square / n);
10+
// Calculate column based on row direction
11+
let col: number;
12+
if (row % 2 === 0) {
13+
// Even rows (from bottom): left to right
14+
col = square % n;
15+
} else {
16+
// Odd rows (from bottom): right to left
17+
col = n - 1 - (square % n);
18+
}
19+
// Convert to board coordinates (0 is top row in board)
20+
return [n - 1 - row, col];
21+
}
22+
23+
// BFS to find shortest path
24+
const target = n * n;
25+
const queue: [number, number][] = [[1, 0]]; // [current_square, num_moves]
26+
const visited = new Set<number>([1]);
27+
28+
while (queue.length > 0) {
29+
const [curr, moves] = queue.shift()!;
30+
31+
// Try all possible dice rolls (1 to 6)
32+
for (let dice = 1; dice <= 6; dice++) {
33+
let nextSquare = curr + dice;
34+
35+
// Check if we've gone beyond the board
36+
if (nextSquare > target) {
37+
break;
38+
}
39+
40+
// Get the board position for this square
41+
const [r, c] = getPosition(nextSquare);
42+
43+
// Check if there's a snake or ladder
44+
if (board[r][c] !== -1) {
45+
nextSquare = board[r][c];
46+
}
47+
48+
// Check if we've reached the target
49+
if (nextSquare === target) {
50+
return moves + 1;
51+
}
52+
53+
// Add to queue if not visited
54+
if (!visited.has(nextSquare)) {
55+
visited.add(nextSquare);
56+
queue.push([nextSquare, moves + 1]);
57+
}
58+
}
59+
}
60+
61+
// If we can't reach the target
62+
return -1;
63+
}
64+
65+
// Test cases
66+
console.log("Example 1:");
67+
const board1 = [
68+
[-1,-1,-1,-1,-1,-1],
69+
[-1,-1,-1,-1,-1,-1],
70+
[-1,-1,-1,-1,-1,-1],
71+
[-1,35,-1,-1,13,-1],
72+
[-1,-1,-1,-1,-1,-1],
73+
[-1,15,-1,-1,-1,-1]
74+
];
75+
console.log(`Input: board = ${JSON.stringify(board1)}`);
76+
console.log(`Output: ${snakesAndLadders(board1)}`); // Expected: 4
77+
console.log(`Explanation: In the beginning, you start at square 1 (at row 5, column 0).
78+
You decide to move to square 2 and must take the ladder to square 15.
79+
You then decide to move to square 17 and must take the snake to square 13.
80+
You then decide to move to square 14 and must take the ladder to square 35.
81+
You then decide to move to square 36, ending the game.
82+
This is the lowest possible number of moves to reach the last square, so return 4.`);
83+
84+
console.log("\nExample 2:");
85+
const board2 = [[-1,-1],[-1,3]];
86+
console.log(`Input: board = ${JSON.stringify(board2)}`);
87+
console.log(`Output: ${snakesAndLadders(board2)}`); // Expected: 1
88+
89+
export { snakesAndLadders };
90+
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_90_snakes_and_ladders import Solution
4+
from typing import Optional, List
5+
6+
7+
class SnakesAndLaddersTestCase(unittest.TestCase):
8+
9+
def test_example_1(self):
10+
"""
11+
Example 1:
12+
Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
13+
Output: 4
14+
Explanation:
15+
In the beginning, you start at square 1 (at row 5, column 0).
16+
You decide to move to square 2 and must take the ladder to square 15.
17+
You then decide to move to square 17 and must take the snake to square 13.
18+
You then decide to move to square 14 and must take the ladder to square 35.
19+
You then decide to move to square 36, ending the game.
20+
This is the lowest possible number of moves to reach the last square, so return 4.
21+
"""
22+
solution = Solution()
23+
board = [
24+
[-1, -1, -1, -1, -1, -1],
25+
[-1, -1, -1, -1, -1, -1],
26+
[-1, -1, -1, -1, -1, -1],
27+
[-1, 35, -1, -1, 13, -1],
28+
[-1, -1, -1, -1, -1, -1],
29+
[-1, 15, -1, -1, -1, -1]
30+
]
31+
expected = 4
32+
33+
result = solution.snakesAndLadders(board)
34+
self.assertEqual(result, expected)
35+
36+
def test_example_2(self):
37+
"""
38+
Example 2:
39+
Input: board = [[-1,-1],[-1,3]]
40+
Output: 1
41+
"""
42+
solution = Solution()
43+
board = [[-1, -1], [-1, 3]]
44+
expected = 1
45+
46+
result = solution.snakesAndLadders(board)
47+
self.assertEqual(result, expected)
48+

0 commit comments

Comments
 (0)