forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Samir Paul
committed
May 25, 2022
1 parent
4664254
commit 8471ee2
Showing
8 changed files
with
315 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# https://www.geeksforgeeks.org/check-if-a-word-exists-in-a-grid-or-not/ | ||
|
||
''' | ||
Given a 2D grid of characters and a word, the task is to check if that word exists in the grid or not. A word can be matched in 4 directions at any point. | ||
The 4 directions are, Horizontally Left and Right, Vertically Up and Down. | ||
''' | ||
|
||
r = 4 | ||
c = 4 | ||
|
||
# Function to check if a word exists | ||
# in a grid starting from the first | ||
# match in the grid level: index till | ||
# which pattern is matched x, y: current | ||
# position in 2D array | ||
def findmatch(mat, pat, x, y, | ||
nrow, ncol, level) : | ||
|
||
l = len(pat) | ||
|
||
# Pattern matched | ||
if (level == l) : | ||
return True | ||
|
||
# Out of Boundary | ||
if (x < 0 or y < 0 or | ||
x >= nrow or y >= ncol) : | ||
return False | ||
|
||
# If grid matches with a letter | ||
# while recursion | ||
if (mat[x][y] == pat[level]) : | ||
|
||
# Marking this cell as visited | ||
temp = mat[x][y] | ||
mat[x].replace(mat[x][y], "#") | ||
|
||
# finding subpattern in 4 directions | ||
res = (findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | | ||
findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | | ||
findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | | ||
findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1)) | ||
|
||
# marking this cell as unvisited again | ||
mat[x].replace(mat[x][y], temp) | ||
return res | ||
|
||
else : # Not matching then false | ||
return False | ||
|
||
# Function to check if the word | ||
# exists in the grid or not | ||
def checkMatch(mat, pat, nrow, ncol) : | ||
|
||
l = len(pat) | ||
|
||
# if total characters in matrix is | ||
# less then pattern length | ||
if (l > nrow * ncol) : | ||
return False | ||
|
||
# Traverse in the grid | ||
for i in range(nrow) : | ||
for j in range(ncol) : | ||
|
||
# If first letter matches, then | ||
# recur and check | ||
if (mat[i][j] == pat[0]) : | ||
if (findmatch(mat, pat, i, j, | ||
nrow, ncol, 0)) : | ||
return True | ||
return False | ||
|
||
# Driver Code | ||
if __name__ == "__main__" : | ||
|
||
grid = ["axmy", "bgdf", | ||
"xeet", "raks"] | ||
|
||
# Function to check if word | ||
# exists or not | ||
if (checkMatch(grid, "geeks", r, c)) : | ||
print("Yes") | ||
else : | ||
print("No") | ||
|
||
# This code is contributed by Ryuga |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/ | ||
|
||
# Python3 program to search a word in a 2D grid | ||
class GFG: | ||
|
||
def __init__(self): | ||
self.R = None | ||
self.C = None | ||
self.dir = [[-1, 0], [1, 0], [1, 1], | ||
[1, -1], [-1, -1], [-1, 1], | ||
[0, 1], [0, -1]] | ||
|
||
# This function searches in all 8-direction | ||
# from point(row, col) in grid[][] | ||
def search2D(self, grid, row, col, word): | ||
|
||
# If first character of word doesn't match | ||
# with the given starting point in grid. | ||
if grid[row][col] != word[0]: | ||
return False | ||
|
||
# Search word in all 8 directions | ||
# starting from (row, col) | ||
for x, y in self.dir: | ||
|
||
# Initialize starting point | ||
# for current direction | ||
rd, cd = row + x, col + y | ||
flag = True | ||
|
||
# First character is already checked, | ||
# match remaining characters | ||
for k in range(1, len(word)): | ||
|
||
# If out of bound or not matched, break | ||
if (0 <= rd <self.R and | ||
0 <= cd < self.C and | ||
word[k] == grid[rd][cd]): | ||
|
||
# Moving in SAME particular direction | ||
rd += x | ||
cd += y | ||
else: | ||
flag = False | ||
break | ||
|
||
# If all character matched, then | ||
# value of flag must be false | ||
if flag: | ||
return True | ||
return False | ||
|
||
# Searches given word in a given matrix | ||
# in all 8 directions | ||
def patternSearch(self, grid, word): | ||
|
||
# Rows and columns in given grid | ||
self.R = len(grid) | ||
self.C = len(grid[0]) | ||
|
||
# Consider every point as starting point | ||
# and search given word | ||
for row in range(self.R): | ||
for col in range(self.C): | ||
if self.search2D(grid, row, col, word): | ||
print("pattern found at " + | ||
str(row) + ', ' + str(col)) | ||
|
||
# Driver Code | ||
if __name__=='__main__': | ||
grid = ["GEEKSFORGEEKS", | ||
"GEEKSQUIZGEEK", | ||
"IDEQAPRACTICE"] | ||
gfg = GFG() | ||
gfg.patternSearch(grid, 'GEEKS') | ||
print('') | ||
gfg.patternSearch(grid, 'EEE') | ||
|
||
# This code is contributed by Yezheng Li | ||
|
||
|
||
''' | ||
Time complexity: O(R*C*8*len(str)). | ||
All the cells will be visited and traversed in all 8 directions, where R and C is side of matrix so time complexity is O(R*C). | ||
Auxiliary Space: O(1). As no extra space is needed. | ||
''' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# https://leetcode.com/problems/longest-common-prefix/ | ||
|
||
class Solution: | ||
def longestCommonPrefix(self, strs: List[str]) -> str: | ||
res = "" | ||
for i in range(len(strs[0])): | ||
for st in strs: | ||
if i == len(st) or strs[0][i] != st[i]: | ||
return res | ||
res += strs[0][i] | ||
|
||
return res | ||
|
||
|
27 changes: 27 additions & 0 deletions
27
17_Bit-Manipulation/11. Power Set using Bit Manipulation.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# https://practice.geeksforgeeks.org/problems/power-set4302/1# | ||
# https://youtu.be/b7AYbpM5YrE | ||
|
||
''' | ||
say p is total numer of power sets. In binary form 1 to p if we select | ||
letter of position where 1 bit then we get all the combinations. | ||
Then sort the result. | ||
''' | ||
|
||
class Solution: | ||
def AllPossibleStrings(self, s): | ||
# Code here | ||
n = len(s) | ||
p = 2 ** n # total number of power sets | ||
res = [] | ||
for i in range(1, p): | ||
tmp = '' | ||
for j in range(n): | ||
if i & (1 << j): | ||
tmp += s[j] | ||
res.append(tmp) | ||
|
||
return sorted(res) | ||
|
||
# Time: O(2^n * n) | ||
# Space: O(n) | ||
|
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
30-Days-SDE-Sheet-Practice/12. Day 12 Trie/03. Maximum XOR of Two Numbers in an Array.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
# https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ | ||
|
||
''' | ||
Insert all the elements of nums in a trie with bit values in respective position. | ||
where every node can have 2 children either with 0 key or 1 key. | ||
As XOR is a inequality detector so we try to maximize the inequality between num and node. | ||
So that the XOR of num and value of node will give the max value. | ||
So we do the following steps While traversing the num from 31'th bit position to 0'th bit position: | ||
If the current bit of num is 1 then we try to move the cur pointer towards the child with 0 key. | ||
And if the current bit of num is 0 then we try to move the cur pointer towards the child with 1 key. | ||
''' | ||
|
||
class TrieNode: | ||
def __init__(self): | ||
self.children = {} | ||
self.val = -1 # used to store the value of entire number at the end of trie node | ||
|
||
class Trie: | ||
def __init__(self): | ||
self.root = TrieNode() # object of trienode class | ||
|
||
def addNum(self, num): | ||
cur = self.root # every time start from root | ||
for i in range(31, -1, -1): | ||
bit = 1 if num & (1 << i) else 0 # bit value i'th position of num | ||
if bit not in cur.children: | ||
cur.children[bit] = TrieNode() | ||
cur = cur.children[bit] | ||
cur.val = num # storing the value of entire num at the end of trie node | ||
|
||
|
||
class Solution: | ||
def findMaximumXOR(self, nums: List[int]) -> int: | ||
trie = Trie() # creating object of Trie class | ||
for num in nums: # adding all num to the trie structure | ||
trie.addNum(num) | ||
|
||
res = 0 | ||
for num in nums: | ||
cur = trie.root # every time start cur pointer from root | ||
for i in range(31, -1, -1): | ||
bit = 1 if num & (1 << i) else 0 # bit value of i'th position of num | ||
if bit == 1: # try to move towards opposite key ie. 0 | ||
if 0 in cur.children: # opposit key 0 exist then defenetly go towards the child 0 | ||
cur = cur.children[0] | ||
else: # opposit key 0 not exist so we have only option to go towards what we have ie. 1 | ||
cur = cur.children[1] | ||
else: # bit == 0 # try to move towards opposite key ie. 1 | ||
if 1 in cur.children: # opposit key 1 exist then defenetly go towards the child 1 | ||
cur = cur.children[1] | ||
else: # opposit key 1 not exist so we have only option to go towards what we have ie. 0 | ||
cur = cur.children[0] | ||
# as we tried to maximize the inequality between cur.val and num so XOR of them will give max value | ||
res = max(res, cur.val ^ num) | ||
|
||
return res | ||
|
||
|
||
|
29 changes: 29 additions & 0 deletions
29
30-Days-SDE-Sheet-Practice/12. Day 12 Trie/03. Number of Distinct Substrings in a String.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# https://www.codingninjas.com/codestudio/problems/count-distinct-substrings_985292 | ||
# https://youtu.be/RV0QeTyHZxo | ||
class TrieNode: | ||
def __init__(self): | ||
self.children = {} | ||
|
||
class Trie: | ||
def __init__(self): | ||
self.root = TrieNode() | ||
def solve(self, s): | ||
res = 0 | ||
for i in range(len(s)): | ||
cur = self.root | ||
for j in range(i, len(s)): | ||
if s[j] not in cur.children: | ||
cur.children[s[j]] = TrieNode() | ||
res += 1 | ||
cur = cur.children[s[j]] | ||
return res + 1 # +1 for empty substring "" | ||
|
||
def countDistinctSubstrings(s): | ||
trie = Trie() | ||
return trie.solve(s) | ||
|
||
|
||
# Time: O(N^2) | ||
# Space: It is hard to predict spcace taken tries. It depends on the distinct elements of s. But as we are using only necessary keys in trie hashmap not all 26 keys so at max space can be N^2 | ||
# Space: in worst case O(N^2) | ||
|