Skip to content

Instantly share code, notes, and snippets.

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for idx,num in enumerate(nums):
req = target - num
if req in seen:
return [seen[req], idx]
seen[num] = idx
@mdpabel
mdpabel / scope.py
Created January 12, 2023 11:08
Python - Global, Local and Nonlocal Variables
v = 0 # global variable
def a():
def test(n):
nonlocal m # used in nested function whose local scope is not defined
global v # outside of function or in global scope
if n == 5:
return n
t = test(n + 1) # local variable
def isUnival(root, val):
if root is None:
return True
if root.val != val:
return False
left = isUnival(root.left, val)
right = isUnival(root.right, val)
if not left or not right:
@mdpabel
mdpabel / wordsFromString.py
Created November 22, 2022 06:25
Words from string
s = " hello bangladesh"
li = []
startIdx = 0
for i in range(len(s)):
if s[i] == " " and s[startIdx] != " ":
li.append(s[startIdx : i])
startIdx = i
elif s[startIdx] == " ":
@mdpabel
mdpabel / sol.js
Created September 17, 2022 13:09
Infinite nexted array sum
const arr = [
1,
[2],
[[3]],
[[[4]]],
[5],
[[[[[[[[[[[[7]]]]]]]], 1]]]],
7,
[[[10], [[[[[[[[1]]]]]]]]]],
];
@mdpabel
mdpabel / solveNQueens.py
Last active September 15, 2022 16:45
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
def canPlace(board, n, row, col):
# col
for i in range(row):
if board[i][col]:
return False
# left diagonal
from collections import Counter
from heapq import heappush, heappop, heappushpop
class Item(object):
def __init__(self, word, freq):
self.word = word
self.freq = freq
def __lt__(self, other):
if self.freq == other.freq:
@mdpabel
mdpabel / swappingEvenOdd.js
Created August 15, 2022 14:31
even odd swapping without using extra space
const arr = [1,5,2,9,7,6]
/**
1 5 9 7 2 6
l = 1
r = 4
1,5,2,9,7,6
2 odd ? l++
2 even ? r--
else : l
@mdpabel
mdpabel / strToWords.py
Created August 14, 2022 14:44
convert integers into words
"""
"41234"
one thousand, two hundred and thirty four
last 2 digits
44 = fourty + four
34 = thirty + four
24 = twinty + four