Initial migration
This commit is contained in:
commit
6e36b869c2
63 changed files with 6350 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
.vscode
|
||||||
|
*.dSYM
|
51
binary_search/c/binary_iterative.c
Normal file
51
binary_search/c/binary_iterative.c
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
// Binary Search in C
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int binarySearch(int array[], int x, int low, int high)
|
||||||
|
/**
|
||||||
|
* Binary search implementation.
|
||||||
|
* int array[] - sorted array of INT to search for
|
||||||
|
* x - INT value for searching
|
||||||
|
* low - initial search starting index
|
||||||
|
* high - initial last array index
|
||||||
|
*/
|
||||||
|
{
|
||||||
|
// Repeat until the pointers low and high meet each other
|
||||||
|
while (low <= high)
|
||||||
|
{
|
||||||
|
// Calculating mid position of an array
|
||||||
|
int mid = low + (high - low) / 2;
|
||||||
|
|
||||||
|
// If value of center object == value to search for
|
||||||
|
if (array[mid] == x)
|
||||||
|
// Return it
|
||||||
|
return mid;
|
||||||
|
|
||||||
|
// If mid value is less than value to search for
|
||||||
|
if (array[mid] < x)
|
||||||
|
// Move low border to the right
|
||||||
|
low = mid + 1;
|
||||||
|
|
||||||
|
// If mid value is greater than value to search for
|
||||||
|
else
|
||||||
|
// Move high border to mid-1 position
|
||||||
|
high = mid - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no value found - return -1
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void)
|
||||||
|
{
|
||||||
|
int array[] = {3, 4, 5, 6, 7, 8, 9};
|
||||||
|
int n = sizeof(array) / sizeof(array[0]);
|
||||||
|
int x = 8;
|
||||||
|
int result = binarySearch(array, x, 0, n - 1);
|
||||||
|
if (result == -1)
|
||||||
|
printf("Not found");
|
||||||
|
else
|
||||||
|
printf("Element is found at index %d", result);
|
||||||
|
return 0;
|
||||||
|
}
|
33
binary_search/c/binary_recursive.c
Normal file
33
binary_search/c/binary_recursive.c
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
// Binary Search in C
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int binarySearch(int array[], int x, int low, int high) {
|
||||||
|
if (high >= low) {
|
||||||
|
int mid = low + (high - low) / 2;
|
||||||
|
|
||||||
|
// If found at mid, then return it
|
||||||
|
if (array[mid] == x)
|
||||||
|
return mid;
|
||||||
|
|
||||||
|
// Search the left half
|
||||||
|
if (array[mid] > x)
|
||||||
|
return binarySearch(array, x, low, mid - 1);
|
||||||
|
|
||||||
|
// Search the right half
|
||||||
|
return binarySearch(array, x, mid + 1, high);
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
int array[] = {3, 4, 5, 6, 7, 8, 9};
|
||||||
|
int n = sizeof(array) / sizeof(array[0]);
|
||||||
|
int x = 4;
|
||||||
|
int result = binarySearch(array, x, 0, n - 1);
|
||||||
|
if (result == -1)
|
||||||
|
printf("Not found");
|
||||||
|
else
|
||||||
|
printf("Element is found at index %d", result);
|
||||||
|
}
|
31
binary_search/python/binary_iterative.py
Normal file
31
binary_search/python/binary_iterative.py
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
# Binary Search in python
|
||||||
|
|
||||||
|
|
||||||
|
def binarySearch(array, x, low, high):
|
||||||
|
|
||||||
|
# Repeat until the pointers low and high meet each other
|
||||||
|
while low <= high:
|
||||||
|
|
||||||
|
mid = low + (high - low)//2
|
||||||
|
|
||||||
|
if array[mid] == x:
|
||||||
|
return mid
|
||||||
|
|
||||||
|
elif array[mid] < x:
|
||||||
|
low = mid + 1
|
||||||
|
|
||||||
|
else:
|
||||||
|
high = mid - 1
|
||||||
|
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
array = [3, 4, 5, 6, 7, 8, 9]
|
||||||
|
x = 4
|
||||||
|
|
||||||
|
result = binarySearch(array, x, 0, len(array)-1)
|
||||||
|
|
||||||
|
if result != -1:
|
||||||
|
print("Element is present at index " + str(result))
|
||||||
|
else:
|
||||||
|
print("Not found")
|
34
binary_search/python/binary_recursive.py
Normal file
34
binary_search/python/binary_recursive.py
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
# Binary Search in python
|
||||||
|
|
||||||
|
|
||||||
|
def binarySearch(array, x, low, high):
|
||||||
|
|
||||||
|
if high >= low:
|
||||||
|
|
||||||
|
mid = low + (high - low)//2
|
||||||
|
|
||||||
|
# If found at mid, then return it
|
||||||
|
if array[mid] == x:
|
||||||
|
return mid
|
||||||
|
|
||||||
|
# Search the left half
|
||||||
|
elif array[mid] > x:
|
||||||
|
return binarySearch(array, x, low, mid-1)
|
||||||
|
|
||||||
|
# Search the right half
|
||||||
|
else:
|
||||||
|
return binarySearch(array, x, mid + 1, high)
|
||||||
|
|
||||||
|
else:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
array = [3, 4, 5, 6, 7, 8, 9]
|
||||||
|
x = 4
|
||||||
|
|
||||||
|
result = binarySearch(array, x, 0, len(array)-1)
|
||||||
|
|
||||||
|
if result != -1:
|
||||||
|
print("Element is present at index " + str(result))
|
||||||
|
else:
|
||||||
|
print("Not found")
|
55
grokaem/fast_sorting/recursion.py
Normal file
55
grokaem/fast_sorting/recursion.py
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
# Task 4.1: Write a code with recursion for calculating summ of all array entries
|
||||||
|
def calculate_recursion_summ(array_of_ints: List[int]) -> int:
|
||||||
|
if len(array_of_ints) == 0:
|
||||||
|
return 0
|
||||||
|
return array_of_ints[0] + calculate_recursion_summ(array_of_ints[1:])
|
||||||
|
|
||||||
|
|
||||||
|
print(calculate_recursion_summ([5, 5, 5, 5, 5]))
|
||||||
|
|
||||||
|
|
||||||
|
# Task 4.2: Write a code with recursion for calculating the amount of elements in List
|
||||||
|
def calculate_list_length(array_of_ints: List[int]) -> int:
|
||||||
|
if len(array_of_ints) == 1:
|
||||||
|
return 1
|
||||||
|
return 1 + calculate_list_length(array_of_ints[1:])
|
||||||
|
|
||||||
|
|
||||||
|
print(calculate_list_length([1, 2, 3, 4, 5, 6, 7, 8]))
|
||||||
|
|
||||||
|
|
||||||
|
# Task 4.3: Write a code to find a highest list value with recursion
|
||||||
|
def find_highest_value_in_lits(array_of_ints: List[int]) -> int:
|
||||||
|
if len(array_of_ints) == 1:
|
||||||
|
return array_of_ints[0]
|
||||||
|
elif len(array_of_ints) == 2:
|
||||||
|
return (
|
||||||
|
array_of_ints[0]
|
||||||
|
if array_of_ints[0] > array_of_ints[1]
|
||||||
|
else array_of_ints[1]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
sub_max = find_highest_value_in_lits(array_of_ints[1:])
|
||||||
|
return array_of_ints[0] if array_of_ints[0] > sub_max else sub_max
|
||||||
|
|
||||||
|
|
||||||
|
print(find_highest_value_in_lits([1, 2, 3, 4, 5, 4, 3, 2, 1, 1231]))
|
||||||
|
|
||||||
|
|
||||||
|
# Task 4.4: Make binary search using recursion
|
||||||
|
def binary_search(array_of_ints: List[int], target_value: int) -> Optional[int]:
|
||||||
|
array_len = len(array_of_ints)
|
||||||
|
if array_len == 1:
|
||||||
|
return array_of_ints[0] if array_of_ints[0] == target_value else None
|
||||||
|
max_left = array_of_ints[array_len // 2]
|
||||||
|
return (
|
||||||
|
binary_search(array_of_ints[: array_len // 2], target_value)
|
||||||
|
if target_value < max_left
|
||||||
|
else binary_search(array_of_ints[array_len // 2:], target_value)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
print(binary_search([1, 2, 3, 4, 5], 4))
|
50
grokaem/graphs/bfs.py
Normal file
50
grokaem/graphs/bfs.py
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
|
||||||
|
# Dummy function to check that person is selling mangos
|
||||||
|
def person_is_seller(name: str) -> bool:
|
||||||
|
# If last person letter is "m" than he is mango seller
|
||||||
|
return name[-1] == "m"
|
||||||
|
|
||||||
|
|
||||||
|
# Implementation of BFS of example graph
|
||||||
|
def bfs():
|
||||||
|
# Modeling graph using hash map
|
||||||
|
graph = {}
|
||||||
|
graph["me"] = ["alice", "bob", "claire"]
|
||||||
|
graph["bob"] = ["anuj", "peggy"]
|
||||||
|
graph["alice"] = ["peggy"]
|
||||||
|
graph["claire"] = ["tom", "jonny"]
|
||||||
|
graph["anuj"] = []
|
||||||
|
graph["peggy"] = []
|
||||||
|
graph["tom"] = []
|
||||||
|
graph["jonny"] = []
|
||||||
|
|
||||||
|
# Creating queue for checking
|
||||||
|
search_queue = deque()
|
||||||
|
|
||||||
|
# Declaring searched persons list for avoiding infinite loop situation
|
||||||
|
searched = []
|
||||||
|
|
||||||
|
# Adding first people to queue, starting from me
|
||||||
|
search_queue += graph["me"]
|
||||||
|
|
||||||
|
# Start searching
|
||||||
|
while search_queue:
|
||||||
|
# Getting first person from queue
|
||||||
|
person = search_queue.popleft()
|
||||||
|
# Checking that person is already searched
|
||||||
|
if person not in searched:
|
||||||
|
if person_is_seller(person):
|
||||||
|
print("{name} is a mago seller!".format(name=person))
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
# Adding new neighbours to queue
|
||||||
|
search_queue += graph[person]
|
||||||
|
# Add current searched person to searched list
|
||||||
|
searched.append(person)
|
||||||
|
print("No mango sellers in your friends list :(")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
bfs()
|
11
grokaem/graphs/bfs_graph.md
Normal file
11
grokaem/graphs/bfs_graph.md
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
A(me) --> B(alice)
|
||||||
|
A --> C(bob)
|
||||||
|
A --> D(claire)
|
||||||
|
B --> P(peggy)
|
||||||
|
C --> P
|
||||||
|
C --> AN(anuj)
|
||||||
|
D --> T(tom)
|
||||||
|
D --> J(jonny)
|
||||||
|
```
|
130
grokaem/graphs/dijkstra.py
Normal file
130
grokaem/graphs/dijkstra.py
Normal file
|
@ -0,0 +1,130 @@
|
||||||
|
# First - initializing the graph
|
||||||
|
graph = {}
|
||||||
|
|
||||||
|
# Put first element in graph
|
||||||
|
graph["start"] = {}
|
||||||
|
graph["start"]["a"] = 6
|
||||||
|
graph["start"]["b"] = 2
|
||||||
|
|
||||||
|
# Put A element in graph
|
||||||
|
graph["a"] = {}
|
||||||
|
graph["a"]["fin"] = 1
|
||||||
|
|
||||||
|
# Put B element in graph
|
||||||
|
graph["b"] = {}
|
||||||
|
graph["b"]["fin"] = 5
|
||||||
|
graph["b"]["a"] = 3
|
||||||
|
|
||||||
|
# Put last element in graph
|
||||||
|
graph["fin"] = {}
|
||||||
|
|
||||||
|
# Now we need to declare "costs" hash table
|
||||||
|
# Costs table shows how much time needed to reach to this node from the starting node
|
||||||
|
|
||||||
|
# Settings up infinity value
|
||||||
|
infinity = float("inf")
|
||||||
|
|
||||||
|
# initializing "costs" hash-table
|
||||||
|
costs = {}
|
||||||
|
costs["a"] = 6
|
||||||
|
costs["b"] = 2
|
||||||
|
costs["fin"] = infinity
|
||||||
|
|
||||||
|
# We also needed "parents" hash-table
|
||||||
|
parents = {}
|
||||||
|
parents["a"] = "start"
|
||||||
|
parents["b"] = "start"
|
||||||
|
parents["fin"] = None
|
||||||
|
|
||||||
|
# ------- Notebook graph example -------
|
||||||
|
|
||||||
|
graph_notebook = {}
|
||||||
|
|
||||||
|
graph_notebook["a"] = {}
|
||||||
|
graph_notebook["a"]["b"] = 1
|
||||||
|
graph_notebook["a"]["d"] = 10
|
||||||
|
|
||||||
|
graph_notebook["b"] = {}
|
||||||
|
graph_notebook["b"]["c"] = 2
|
||||||
|
|
||||||
|
graph_notebook["c"] = {}
|
||||||
|
graph_notebook["c"]["d"] = 3
|
||||||
|
graph_notebook["c"]["e"] = 15
|
||||||
|
|
||||||
|
graph_notebook["d"] = {}
|
||||||
|
graph_notebook["d"]["e"] = 1
|
||||||
|
|
||||||
|
graph_notebook["e"] = {}
|
||||||
|
|
||||||
|
costs_notebook = {}
|
||||||
|
costs_notebook["b"] = 1
|
||||||
|
costs_notebook["d"] = 10
|
||||||
|
costs_notebook["c"] = infinity
|
||||||
|
costs_notebook["e"] = infinity
|
||||||
|
|
||||||
|
# We also needed "parents" hash-table
|
||||||
|
parents_notebook = {}
|
||||||
|
parents_notebook["b"] = "a"
|
||||||
|
parents_notebook["d"] = "a"
|
||||||
|
parents_notebook["c"] = None
|
||||||
|
parents_notebook["e"] = None
|
||||||
|
|
||||||
|
|
||||||
|
def dijkstra_algo(graph, costs, parents):
|
||||||
|
# We need to store processed nodes list
|
||||||
|
processed = []
|
||||||
|
|
||||||
|
# First we need to define function for finding the lowest cost node to process it
|
||||||
|
def find_lowest_cost_node(costs):
|
||||||
|
lowest_cost = float("inf")
|
||||||
|
lowest_cost_node = None
|
||||||
|
for node in costs:
|
||||||
|
cost = costs[node]
|
||||||
|
if cost < lowest_cost and node not in processed:
|
||||||
|
lowest_cost = cost
|
||||||
|
lowest_cost_node = node
|
||||||
|
return lowest_cost_node
|
||||||
|
|
||||||
|
# And now we initiate the algorithm
|
||||||
|
node = find_lowest_cost_node(costs)
|
||||||
|
step = 1
|
||||||
|
while node is not None:
|
||||||
|
print(f"Step {step}")
|
||||||
|
print(f"Current data:\nParents: {parents}\nCosts: {costs}\n\n")
|
||||||
|
print(f"current lowest node: {node}. Start to inspect it")
|
||||||
|
cost = costs[node]
|
||||||
|
neighbors = graph[node]
|
||||||
|
print(f"Cost of node {node} = {cost}")
|
||||||
|
print(f"Neighbors of node {node} = {neighbors}")
|
||||||
|
for n in neighbors.keys():
|
||||||
|
print(f" Processing neighbor {n}")
|
||||||
|
new_cost = cost + neighbors[n]
|
||||||
|
print(f" New calculated cost for neighbor {n} = {new_cost}")
|
||||||
|
if costs[n] > new_cost:
|
||||||
|
print(
|
||||||
|
f" New calculated cost {new_cost} is lower than old node cost {costs[n]} so we replace it with new value and new parent {node}"
|
||||||
|
)
|
||||||
|
costs[n] = new_cost
|
||||||
|
parents[n] = node
|
||||||
|
print(
|
||||||
|
f" New costs table:\n {costs}\n New parents table:\n {parents}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f" New calculated cost {new_cost} is greater than old node cost {costs[n]} so we do not touching costs and parents table"
|
||||||
|
)
|
||||||
|
print(f" Costs table:\n {costs}\n Parents table:\n {parents}")
|
||||||
|
print(
|
||||||
|
f"Work with node {node} is finished, so we marking it with processed label"
|
||||||
|
)
|
||||||
|
processed.append(node)
|
||||||
|
node = find_lowest_cost_node(costs)
|
||||||
|
step += 1
|
||||||
|
print("--------------------")
|
||||||
|
|
||||||
|
print(processed)
|
||||||
|
print(parents)
|
||||||
|
print(costs)
|
||||||
|
|
||||||
|
|
||||||
|
dijkstra_algo(graph_notebook, costs_notebook, parents_notebook)
|
11
grokaem/graphs/dijkstra_graph.md
Normal file
11
grokaem/graphs/dijkstra_graph.md
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
B(book) -- 5 -->REC(record)
|
||||||
|
B -- 0 --> P(poster)
|
||||||
|
P -- 35 --> D(drums)
|
||||||
|
REC -- 20 --> D
|
||||||
|
REC -- 15 --> BG(bas guitar)
|
||||||
|
P -- 30 -->BG
|
||||||
|
BG -- 20 --> PIA(piano)
|
||||||
|
D -- 10 --> PIA
|
||||||
|
```
|
8
grokaem/graphs/dijkstra_graph_2.md
Normal file
8
grokaem/graphs/dijkstra_graph_2.md
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
ST(Start) -- 6 --> A
|
||||||
|
ST -- 2 --> B
|
||||||
|
A -- 1 --> F(Finish)
|
||||||
|
B -- 5 --> F
|
||||||
|
B -- 3 --> A
|
||||||
|
```
|
36
grokaem/graphs/implementation.py
Normal file
36
grokaem/graphs/implementation.py
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
graph = {}
|
||||||
|
graph["you"] = ["alice", "bob", "claire"]
|
||||||
|
graph["bob"] = ["anuj", "peggy"]
|
||||||
|
graph["alice"] = ["peggy"]
|
||||||
|
graph["claire"] = ["thom", "jonny"]
|
||||||
|
graph["anuj"] = []
|
||||||
|
graph["peggy"] = []
|
||||||
|
graph["thom"] = []
|
||||||
|
graph["jonny"] = []
|
||||||
|
|
||||||
|
|
||||||
|
def person_is_seller(name):
|
||||||
|
return name[-1] == "z"
|
||||||
|
|
||||||
|
|
||||||
|
def search(name):
|
||||||
|
search_queue = deque()
|
||||||
|
search_queue += graph[name]
|
||||||
|
print(search_queue)
|
||||||
|
searched = []
|
||||||
|
while search_queue:
|
||||||
|
person = search_queue.popleft()
|
||||||
|
if person not in searched:
|
||||||
|
if person_is_seller(person):
|
||||||
|
print(person + " is a mango seller!")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
search_queue += graph[person]
|
||||||
|
searched.append(person)
|
||||||
|
print(searched)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
search("you")
|
0
grokaem/greedy_algos/__init__.py
Normal file
0
grokaem/greedy_algos/__init__.py
Normal file
42
grokaem/greedy_algos/set_covering.py
Normal file
42
grokaem/greedy_algos/set_covering.py
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
# Штаты, которые необходимо покрыть
|
||||||
|
states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"])
|
||||||
|
|
||||||
|
# Станции, на которых вещают имеющиеся радиостанции
|
||||||
|
stations = {}
|
||||||
|
stations["kone"] = set(["id", "nv", "ut"])
|
||||||
|
stations["ktwo"] = set(["wa", "id", "mt"])
|
||||||
|
stations["kthree"] = set(["or", "nv", "ca"])
|
||||||
|
stations["kfour"] = set(["nv", "ut"])
|
||||||
|
stations["kfive"] = set(["ca", "az"])
|
||||||
|
|
||||||
|
# Набор радиостанций, покрывающий все необходимые штаты
|
||||||
|
final_stations = set()
|
||||||
|
|
||||||
|
while states_needed:
|
||||||
|
best_station = None
|
||||||
|
# Штаты, обслуживаемые этой станцией, которые еще не входят в текущее покрытие
|
||||||
|
states_covered = set()
|
||||||
|
|
||||||
|
# Перебор всех радиостанций и поиск наилучшей из них
|
||||||
|
for station, states_for_station in stations.items():
|
||||||
|
# Пересечение множеств необходимых к покрытию станций с станциями для
|
||||||
|
# итерируемой радиостанции
|
||||||
|
covered = states_needed & states_for_station
|
||||||
|
|
||||||
|
# Если длина множества пересечения больше длины покрытия лучшей текущей станции
|
||||||
|
# Иными словами в пересечение входит больше покрываемых штатов, чем для текущей
|
||||||
|
# лучшей станции
|
||||||
|
if len(covered) > len(states_covered):
|
||||||
|
# Назначаем эту станцию лучшей
|
||||||
|
best_station = station
|
||||||
|
# Переопределяем штаты, покрываемые лучшей на данный момент станцией
|
||||||
|
states_covered = covered
|
||||||
|
|
||||||
|
# После прохождения цикла лучшая станция добавляется в список станций для покрытия
|
||||||
|
final_stations.add(best_station)
|
||||||
|
|
||||||
|
# Необходимо вычесть из нужных для покрытия станций те, которые входят в найденную
|
||||||
|
# станцию
|
||||||
|
states_needed -= states_covered
|
||||||
|
|
||||||
|
print(final_stations)
|
BIN
grokaem/Грокаем алгоритмы.pdf
Normal file
BIN
grokaem/Грокаем алгоритмы.pdf
Normal file
Binary file not shown.
26
leetcode/array_118_pascals_triangle/my_solution.py
Normal file
26
leetcode/array_118_pascals_triangle/my_solution.py
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def generate(self, numRows: int) -> List[List[int]]:
|
||||||
|
if numRows == 1:
|
||||||
|
return [[1]]
|
||||||
|
if numRows == 2:
|
||||||
|
return [[1],[1,1]]
|
||||||
|
result = [[1], [1,1]]
|
||||||
|
for i in range(3, numRows+1):
|
||||||
|
tmp = [0] * i
|
||||||
|
tmp[0] = 1
|
||||||
|
tmp[len(tmp)-1] = 1
|
||||||
|
for j in range(1, len(tmp)-1):
|
||||||
|
prev = result[i-2]
|
||||||
|
tmp[j] = prev[j-1] + prev[j]
|
||||||
|
result.append(tmp)
|
||||||
|
return result
|
||||||
|
|
||||||
|
print(Solution().generate(numRows=5))
|
||||||
|
print("-"*60)
|
||||||
|
print(Solution().generate(numRows=1))
|
||||||
|
print("-"*60)
|
||||||
|
print(Solution().generate(numRows=10))
|
||||||
|
print("-"*60)
|
|
@ -0,0 +1,13 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def maxProfit(self, prices: List[int]) -> int:
|
||||||
|
min_price = prices[0]
|
||||||
|
max_profit = 0
|
||||||
|
|
||||||
|
for price in prices[1:]:
|
||||||
|
max_profit = max(max_profit, price - min_price)
|
||||||
|
min_price = min(min_price, price)
|
||||||
|
|
||||||
|
return max_profit
|
|
@ -0,0 +1,13 @@
|
||||||
|
# Самостоятельно не решил
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def maxProfit(self, prices: List[int]) -> int:
|
||||||
|
return prices[1:]
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.maxProfit(prices=[7, 1, 5, 3, 6, 4]))
|
||||||
|
print(sl1.maxProfit(prices=[7, 6, 4, 3, 1]))
|
||||||
|
print(sl1.maxProfit(prices=[2, 1, 2, 1, 0, 1, 2]))
|
Binary file not shown.
After Width: | Height: | Size: 158 KiB |
20
leetcode/array_169_majority_element/improved_solution.py
Normal file
20
leetcode/array_169_majority_element/improved_solution.py
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def majorityElement(self, nums: List[int]) -> int:
|
||||||
|
majority_limit = len(nums) / 2
|
||||||
|
count_store = {}
|
||||||
|
for elem in nums:
|
||||||
|
try:
|
||||||
|
count_store[elem] += 1
|
||||||
|
except KeyError:
|
||||||
|
count_store[elem] = 1
|
||||||
|
if count_store[elem] > majority_limit:
|
||||||
|
return elem
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
sl2 = Solution()
|
||||||
|
print(sl1.majorityElement(nums=[3, 2, 3]))
|
||||||
|
print(sl1.majorityElement(nums=[2, 2, 1, 1, 1, 2, 2]))
|
20
leetcode/array_169_majority_element/my_solution.py
Normal file
20
leetcode/array_169_majority_element/my_solution.py
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def majorityElement(self, nums: List[int]) -> int:
|
||||||
|
majority_limit = len(nums) / 2
|
||||||
|
count_store = {}
|
||||||
|
for elem in nums:
|
||||||
|
if elem not in count_store.keys():
|
||||||
|
count_store[elem] = 1
|
||||||
|
else:
|
||||||
|
count_store[elem] += 1
|
||||||
|
if count_store[elem] > majority_limit:
|
||||||
|
return elem
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
sl2 = Solution()
|
||||||
|
print(sl1.majorityElement(nums=[3, 2, 3]))
|
||||||
|
print(sl1.majorityElement(nums=[2, 2, 1, 1, 1, 2, 2]))
|
19
leetcode/array_189_rotate_array/my_solution.py
Normal file
19
leetcode/array_189_rotate_array/my_solution.py
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def rotate(self, nums: List[int], k: int) -> None:
|
||||||
|
"""
|
||||||
|
Do not return anything, modify nums in-place instead.
|
||||||
|
"""
|
||||||
|
while k > 0:
|
||||||
|
elem = nums.pop()
|
||||||
|
nums.insert(0, elem)
|
||||||
|
k -= 1
|
||||||
|
return nums
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
sl2 = Solution()
|
||||||
|
print(sl1.rotate(nums=[1, 2, 3, 4, 5, 6, 7], k=3))
|
||||||
|
print(sl1.rotate(nums=[-1, -100, 3, 99], k=2))
|
BIN
leetcode/array_27_remove_element/27_remove_elem.png
Normal file
BIN
leetcode/array_27_remove_element/27_remove_elem.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 128 KiB |
11
leetcode/array_27_remove_element/best_solution.py
Normal file
11
leetcode/array_27_remove_element/best_solution.py
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeElement(self, nums: List[int], val: int) -> int:
|
||||||
|
index = 0
|
||||||
|
for i in range(len(nums)):
|
||||||
|
if nums[i] != val:
|
||||||
|
nums[index] = nums[i]
|
||||||
|
index += 1
|
||||||
|
return index
|
18
leetcode/array_27_remove_element/my_accepted_solution.py
Normal file
18
leetcode/array_27_remove_element/my_accepted_solution.py
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeElement(self, nums: List[int], val: int) -> int:
|
||||||
|
counter = 0
|
||||||
|
nums_iterator_index = len(nums) - 1
|
||||||
|
while nums_iterator_index >= 0:
|
||||||
|
if nums[nums_iterator_index] == val:
|
||||||
|
del nums[nums_iterator_index]
|
||||||
|
else:
|
||||||
|
counter += 1
|
||||||
|
nums_iterator_index -= 1
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
print(Solution().removeElement(nums=[3, 2, 2, 3], val=3))
|
||||||
|
print(Solution().removeElement(nums=[0, 1, 2, 2, 3, 0, 4, 2], val=2))
|
1
leetcode/array_27_remove_element/task.md
Normal file
1
leetcode/array_27_remove_element/task.md
Normal file
|
@ -0,0 +1 @@
|
||||||
|
[link](https://leetcode.com/problems/remove-element/description/?envType=study-plan-v2&envId=top-interview-150)
|
BIN
leetcode/array_28_remove_dublicates_from_sorted_array/26.png
Normal file
BIN
leetcode/array_28_remove_dublicates_from_sorted_array/26.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 145 KiB |
|
@ -0,0 +1,36 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeDuplicates(self, nums: List[int]) -> int:
|
||||||
|
j = 1
|
||||||
|
for i in range(1, len(nums)):
|
||||||
|
if nums[i] != nums[i - 1]:
|
||||||
|
nums[j] = nums[i]
|
||||||
|
j += 1
|
||||||
|
print(nums)
|
||||||
|
return j
|
||||||
|
|
||||||
|
|
||||||
|
print(Solution().removeDuplicates(nums=[1, 1, 2]))
|
||||||
|
print()
|
||||||
|
print(Solution().removeDuplicates(nums=[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
|
||||||
|
|
||||||
|
"""
|
||||||
|
The code starts iterating from i = 1 because we need to compare each element with its
|
||||||
|
previous element to check for duplicates.
|
||||||
|
|
||||||
|
The main logic is inside the for loop:
|
||||||
|
|
||||||
|
1. If the current element nums[i] is not equal to the previous element nums[i - 1],
|
||||||
|
it means we have encountered a new unique element.
|
||||||
|
2. In that case, we update nums[j] with the value of the unique element at nums[i],
|
||||||
|
and then increment j by 1 to mark the next position for a new unique element.
|
||||||
|
3. By doing this, we effectively overwrite any duplicates in the array and only keep
|
||||||
|
the unique elements.
|
||||||
|
|
||||||
|
Once the loop finishes, the value of j represents the length of the resulting array
|
||||||
|
with duplicates removed.
|
||||||
|
|
||||||
|
Finally, we return j as the desired result.
|
||||||
|
"""
|
|
@ -0,0 +1,21 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeDublicates(self, nums: List[int]) -> int:
|
||||||
|
counter = 1
|
||||||
|
nums_unique_index = 0
|
||||||
|
delete_candidates = []
|
||||||
|
for i in range(1, len(nums)):
|
||||||
|
if nums[i] == nums[nums_unique_index]:
|
||||||
|
delete_candidates.append(i)
|
||||||
|
else:
|
||||||
|
nums_unique_index = i
|
||||||
|
counter += 1
|
||||||
|
for index in sorted(delete_candidates, reverse=True):
|
||||||
|
del nums[index]
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
print(Solution().removeDublicates(nums=[1, 1, 2]))
|
||||||
|
print(Solution().removeDublicates(nums=[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
|
|
@ -0,0 +1 @@
|
||||||
|
[link](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150)
|
13
leetcode/array_35_search_insert_position/best_solution.py
Normal file
13
leetcode/array_35_search_insert_position/best_solution.py
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||||
|
if not nums:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
for i, num in enumerate(nums):
|
||||||
|
if num >= target:
|
||||||
|
return i
|
||||||
|
|
||||||
|
return len(nums)
|
|
@ -0,0 +1,33 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||||
|
if len(nums) == 1:
|
||||||
|
return 1 if target > nums[0] else 0
|
||||||
|
max = len(nums) - 1
|
||||||
|
i = 0
|
||||||
|
while i < max:
|
||||||
|
if nums[i] == target:
|
||||||
|
return i
|
||||||
|
if target > nums[i]:
|
||||||
|
i += 1
|
||||||
|
if target < nums[i]:
|
||||||
|
return i
|
||||||
|
return i + 1 if target != nums[i] else i
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=5))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=2))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=7))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3], target=1))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3], target=3))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1], target=0))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1], target=1))
|
41
leetcode/array_35_search_insert_position/my_solution.py
Normal file
41
leetcode/array_35_search_insert_position/my_solution.py
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def binary_search(self, array, x, low, high):
|
||||||
|
if high >= low:
|
||||||
|
mid = low + (high - low) // 2
|
||||||
|
if array[mid] == x:
|
||||||
|
return mid, None, None
|
||||||
|
elif array[mid] > x:
|
||||||
|
return self.binary_search(array, x, low, mid - 1)
|
||||||
|
else:
|
||||||
|
return self.binary_search(array, x, mid + 1, high)
|
||||||
|
else:
|
||||||
|
return None, high, low
|
||||||
|
|
||||||
|
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||||
|
if len(nums) == 1:
|
||||||
|
return 1 if target > nums[0] else 0
|
||||||
|
bingo, high, low = self.binary_search(nums, target, 0, len(nums) - 1)
|
||||||
|
print(f"b: {bingo}")
|
||||||
|
print(f"h: {high}")
|
||||||
|
print(f"l: {low}")
|
||||||
|
if bingo or bingo == 0:
|
||||||
|
return bingo
|
||||||
|
else:
|
||||||
|
return low
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=5))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=2))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3, 5, 6], target=7))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1, 3], target=1))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1], target=0))
|
||||||
|
print("---")
|
||||||
|
print(sl1.searchInsert([1], target=1))
|
24
leetcode/array_36_valid_sudoku/best_solution.py
Normal file
24
leetcode/array_36_valid_sudoku/best_solution.py
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
"""
|
||||||
|
1)It initializes an empty list called "res", which will be used to store all the valid elements in the board.
|
||||||
|
|
||||||
|
2)It loops through each cell in the board using two nested "for" loops.
|
||||||
|
For each cell, it retrieves the value of the element in that cell and stores it in a variable called "element".
|
||||||
|
|
||||||
|
3)If the element is not a dot ('.'), which means it's a valid number, the method adds three tuples to the "res" list:
|
||||||
|
|
||||||
|
The first tuple contains the row index (i) and the element itself.
|
||||||
|
The second tuple contains the element itself and the column index (j).
|
||||||
|
The third tuple contains the floor division of the row index by 3 (i // 3), the floor division of the column index by 3 (j // 3), and the element itself. This tuple represents the 3x3 sub-grid that the current cell belongs to.
|
||||||
|
4)After processing all the cells, the method checks if the length of "res" is equal to the length of the set of "res".
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class Solution(object):
|
||||||
|
def isValidSudoku(self, board):
|
||||||
|
res = []
|
||||||
|
for i in range(9):
|
||||||
|
for j in range(9):
|
||||||
|
element = board[i][j]
|
||||||
|
if element != ".":
|
||||||
|
res += [(i, element), (element, j), (i // 3, j // 3, element)]
|
||||||
|
return len(res) == len(set(res))
|
92
leetcode/array_36_valid_sudoku/my_accepted_solution.py
Normal file
92
leetcode/array_36_valid_sudoku/my_accepted_solution.py
Normal file
|
@ -0,0 +1,92 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def isValidSudoku(self, board: List[List[str]]) -> bool:
|
||||||
|
size = 9
|
||||||
|
cols = {
|
||||||
|
0: [],
|
||||||
|
1: [],
|
||||||
|
2: [],
|
||||||
|
3: [],
|
||||||
|
4: [],
|
||||||
|
5: [],
|
||||||
|
6: [],
|
||||||
|
7: [],
|
||||||
|
8: [],
|
||||||
|
}
|
||||||
|
rows = {
|
||||||
|
0: [],
|
||||||
|
1: [],
|
||||||
|
2: [],
|
||||||
|
3: [],
|
||||||
|
4: [],
|
||||||
|
5: [],
|
||||||
|
6: [],
|
||||||
|
7: [],
|
||||||
|
8: [],
|
||||||
|
}
|
||||||
|
mini_squares = {
|
||||||
|
"00": [],
|
||||||
|
"01": [],
|
||||||
|
"02": [],
|
||||||
|
"10": [],
|
||||||
|
"11": [],
|
||||||
|
"12": [],
|
||||||
|
"20": [],
|
||||||
|
"21": [],
|
||||||
|
"22": [],
|
||||||
|
}
|
||||||
|
for j in range(0, size):
|
||||||
|
mini_second_index = j // 3
|
||||||
|
for i in range(0, size):
|
||||||
|
mini_first_index = i // 3
|
||||||
|
mini_square_index = f"{mini_first_index}{mini_second_index}"
|
||||||
|
value = board[i][j]
|
||||||
|
if value != ".":
|
||||||
|
if (
|
||||||
|
value in cols[j]
|
||||||
|
or value in rows[i]
|
||||||
|
or value in mini_squares[mini_square_index]
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
cols[j].append(value)
|
||||||
|
rows[i].append(value)
|
||||||
|
mini_squares[mini_square_index].append(value)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(
|
||||||
|
sl1.isValidSudoku(
|
||||||
|
board=[
|
||||||
|
["5", "3", ".", ".", "7", ".", ".", ".", "."],
|
||||||
|
["6", ".", ".", "1", "9", "5", ".", ".", "."],
|
||||||
|
[".", "9", "8", ".", ".", ".", ".", "6", "."],
|
||||||
|
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
|
||||||
|
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
|
||||||
|
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
|
||||||
|
[".", "6", ".", ".", ".", ".", "2", "8", "."],
|
||||||
|
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
|
||||||
|
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print("-" * 60)
|
||||||
|
print(
|
||||||
|
sl1.isValidSudoku(
|
||||||
|
board=[
|
||||||
|
["8", "3", ".", ".", "7", ".", ".", ".", "."],
|
||||||
|
["6", ".", ".", "1", "9", "5", ".", ".", "."],
|
||||||
|
[".", "9", "8", ".", ".", ".", ".", "6", "."],
|
||||||
|
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
|
||||||
|
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
|
||||||
|
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
|
||||||
|
[".", "6", ".", ".", ".", ".", "2", "8", "."],
|
||||||
|
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
|
||||||
|
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print("-" * 60)
|
29
leetcode/array_55_jump_game/best_solution.py
Normal file
29
leetcode/array_55_jump_game/best_solution.py
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
"""Explanation
|
||||||
|
|
||||||
|
Imagine you have a car, and you have some distance to travel (the length of the array).
|
||||||
|
This car has some amount of gasoline, and as long as it has gasoline, it can keep
|
||||||
|
traveling on this road (the array). Every time we move up one element in the array,
|
||||||
|
we subtract one unit of gasoline. However, every time we find an amount of gasoline
|
||||||
|
that is greater than our current amount, we "gas up" our car by replacing our current
|
||||||
|
amount of gasoline with this new amount.
|
||||||
|
We keep repeating this process until we either run out of gasoline (and return false),
|
||||||
|
or we reach the end with just enough gasoline (or more to spare), in which case we
|
||||||
|
return true.
|
||||||
|
Note: We can let our gas tank get to zero as long as we are able to gas up at that
|
||||||
|
immediate location (element in the array) that our car is currently at.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def canJump(self, nums: List[int]) -> bool:
|
||||||
|
gas = 0
|
||||||
|
for n in nums:
|
||||||
|
if gas < 0:
|
||||||
|
return False
|
||||||
|
elif n > gas:
|
||||||
|
gas = n
|
||||||
|
gas -= 1
|
||||||
|
|
||||||
|
return True
|
32
leetcode/array_55_jump_game/my_solution.py
Normal file
32
leetcode/array_55_jump_game/my_solution.py
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
# Не решил ...
|
||||||
|
|
||||||
|
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def canJump(self, nums: List[int]) -> bool:
|
||||||
|
def calculate_jump_for_elem(elem, elem_index):
|
||||||
|
if elem == len(nums):
|
||||||
|
return True
|
||||||
|
for jump_distance in range(elem, -1, -1):
|
||||||
|
if (elem_index + jump_distance) == len(nums) - 1:
|
||||||
|
return True
|
||||||
|
if jump_distance == 0:
|
||||||
|
continue
|
||||||
|
jump_index = elem_index + jump_distance
|
||||||
|
if jump_index > len(nums) - 1:
|
||||||
|
continue
|
||||||
|
next_elem = nums[jump_index]
|
||||||
|
return calculate_jump_for_elem(next_elem, jump_index)
|
||||||
|
|
||||||
|
res = calculate_jump_for_elem(nums[0], 0)
|
||||||
|
return res if res else False
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.canJump(nums=[2, 3, 1, 1, 4]))
|
||||||
|
print(sl1.canJump(nums=[3, 2, 1, 0, 4]))
|
||||||
|
print(sl1.canJump(nums=[1]))
|
||||||
|
print(sl1.canJump(nums=[1, 2, 3]))
|
||||||
|
print(sl1.canJump(nums=[2, 5, 0, 0]))
|
31
leetcode/array_66_plus_one/best_solution.py
Normal file
31
leetcode/array_66_plus_one/best_solution.py
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def plusOne(self, digits: List[int]) -> List[int]:
|
||||||
|
|
||||||
|
for i in range(len(digits) - 1, -1, -1):
|
||||||
|
if digits[i] == 9:
|
||||||
|
digits[i] = 0
|
||||||
|
else:
|
||||||
|
digits[i] = digits[i] + 1
|
||||||
|
return digits
|
||||||
|
return [1] + digits
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.plusOne([1, 3, 5, 6]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([1, 2, 3]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([4, 3, 2, 1]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9, 9, 9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([0]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([1, 9, 9, 9, 9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9, 8, 9]))
|
44
leetcode/array_66_plus_one/my_solution.py
Normal file
44
leetcode/array_66_plus_one/my_solution.py
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def plusOne(self, digits: List[int]) -> List[int]:
|
||||||
|
j = len(digits) - 1
|
||||||
|
if j == 0:
|
||||||
|
if digits[0] + 1 < 10:
|
||||||
|
digits[0] = digits[0] + 1
|
||||||
|
return digits
|
||||||
|
else:
|
||||||
|
digits[0] = 1
|
||||||
|
digits.append(0)
|
||||||
|
return digits
|
||||||
|
digits[j] = digits[j] + 1
|
||||||
|
while j >= 1:
|
||||||
|
if digits[j] < 10:
|
||||||
|
return digits
|
||||||
|
if digits[j] == 10:
|
||||||
|
digits[j] = 0
|
||||||
|
digits[j - 1] = digits[j - 1] + 1
|
||||||
|
j -= 1
|
||||||
|
if digits[0] == 10:
|
||||||
|
digits[0] = 1
|
||||||
|
digits.append(0)
|
||||||
|
return digits
|
||||||
|
|
||||||
|
|
||||||
|
sl1 = Solution()
|
||||||
|
print(sl1.plusOne([1, 3, 5, 6]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([1, 2, 3]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([4, 3, 2, 1]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9, 9, 9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([0]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([1, 9, 9, 9, 9]))
|
||||||
|
print("---")
|
||||||
|
print(sl1.plusOne([9, 8, 9]))
|
|
@ -0,0 +1,15 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeDuplicates(self, nums: List[int]) -> int:
|
||||||
|
j = 1
|
||||||
|
for i in range(1, len(nums)):
|
||||||
|
if j == 1 or nums[i] != nums[j - 2]:
|
||||||
|
nums[j] = nums[i]
|
||||||
|
j += 1
|
||||||
|
return j
|
||||||
|
|
||||||
|
|
||||||
|
print(Solution().removeDuplicates(nums=[1, 1, 1, 2, 2, 3]))
|
||||||
|
print(Solution().removeDuplicates(nums=[0, 0, 1, 1, 1, 1, 2, 3, 3]))
|
Binary file not shown.
|
@ -0,0 +1,18 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def removeDuplicates(self, nums: List[int]) -> int:
|
||||||
|
# print(nums)
|
||||||
|
# j = 1
|
||||||
|
# for i in range(1, len(nums)):
|
||||||
|
# if nums[i] != nums[i - 1]:
|
||||||
|
# nums[j] = nums[i]
|
||||||
|
# j += 1
|
||||||
|
# print(nums)
|
||||||
|
# return j
|
||||||
|
# Не решил:(
|
||||||
|
|
||||||
|
|
||||||
|
print(Solution().removeDuplicates(nums=[1, 1, 1, 2, 2, 3]))
|
||||||
|
print(Solution().removeDuplicates(nums=[0, 0, 1, 1, 1, 1, 2, 3, 3]))
|
18
leetcode/array_9_palindrome_number/my_solution.py
Normal file
18
leetcode/array_9_palindrome_number/my_solution.py
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
class Solution:
|
||||||
|
def isPalindrome(self, x: int) -> bool:
|
||||||
|
res = [xx for xx in str(x)]
|
||||||
|
if len(res) == 1:
|
||||||
|
return True
|
||||||
|
i, j = 0, len(res) - 1
|
||||||
|
while i < j/2:
|
||||||
|
if res[i] != len(res) / 2:
|
||||||
|
return False
|
||||||
|
i += 1
|
||||||
|
j -= 1
|
||||||
|
return True
|
||||||
|
|
||||||
|
print(Solution().isPalindrome(x=121))
|
||||||
|
print(Solution().isPalindrome(x=-121))
|
||||||
|
print(Solution().isPalindrome(x=10))
|
||||||
|
print(Solution().isPalindrome(x=0))
|
||||||
|
print(Solution().isPalindrome(x=1000030001))
|
5040
leetcode/container_with_most_water/main.py
Normal file
5040
leetcode/container_with_most_water/main.py
Normal file
File diff suppressed because it is too large
Load diff
0
neetcode/__init__.py
Normal file
0
neetcode/__init__.py
Normal file
0
neetcode/duplicate_integer/__init__.py
Normal file
0
neetcode/duplicate_integer/__init__.py
Normal file
28
neetcode/duplicate_integer/main.py
Normal file
28
neetcode/duplicate_integer/main.py
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def hasDuplicate(self, nums: List[int]) -> bool:
|
||||||
|
if len(nums) == 0:
|
||||||
|
return False
|
||||||
|
res = dict()
|
||||||
|
for entry in nums:
|
||||||
|
is_dublicate = res.get(entry)
|
||||||
|
if is_dublicate:
|
||||||
|
return True
|
||||||
|
res[entry] = True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
input_1 = [1, 2, 3, 3]
|
||||||
|
input_2 = [1, 2, 3, 4]
|
||||||
|
input_3 = []
|
||||||
|
input_4 = [0]
|
||||||
|
input_5 = [1, 2, 2, 2, 2, 3, 1, 1]
|
||||||
|
|
||||||
|
sol = Solution()
|
||||||
|
print(sol.hasDuplicate(input_1))
|
||||||
|
print(sol.hasDuplicate(input_2))
|
||||||
|
print(sol.hasDuplicate(input_3))
|
||||||
|
print(sol.hasDuplicate(input_4))
|
||||||
|
print(sol.hasDuplicate(input_5))
|
0
neetcode/group_anagrams/__init__.py
Normal file
0
neetcode/group_anagrams/__init__.py
Normal file
39
neetcode/group_anagrams/main.py
Normal file
39
neetcode/group_anagrams/main.py
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
from collections import defaultdict
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
|
||||||
|
if len(strs) <= 1:
|
||||||
|
return [strs]
|
||||||
|
result: List[List[str]] = []
|
||||||
|
char_counter: Dict[str, Dict[str, int]] = dict()
|
||||||
|
for word in strs:
|
||||||
|
sorted_word: str = "".join(sorted(word))
|
||||||
|
# Get by sorted_word key
|
||||||
|
sorted_entry = char_counter.get(sorted_word)
|
||||||
|
if sorted_entry:
|
||||||
|
char_counter[sorted_word].append(word)
|
||||||
|
else:
|
||||||
|
char_counter[sorted_word] = [word]
|
||||||
|
for value in char_counter.values():
|
||||||
|
result.append(value)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class NeetcodeSolution:
|
||||||
|
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
|
||||||
|
ans = defaultdict(list)
|
||||||
|
|
||||||
|
for s in strs:
|
||||||
|
count = [0] * 26
|
||||||
|
for c in s:
|
||||||
|
count[ord(c) - ord("a")] += 1
|
||||||
|
ans[tuple(count)].append(s)
|
||||||
|
return ans.values()
|
||||||
|
|
||||||
|
|
||||||
|
s = Solution()
|
||||||
|
strs = ["act", "pots", "tops", "cat", "stodsafjoooop", "hat"]
|
||||||
|
print(s.groupAnagrams(strs))
|
0
neetcode/is_anagram/__init__.py
Normal file
0
neetcode/is_anagram/__init__.py
Normal file
41
neetcode/is_anagram/main.py
Normal file
41
neetcode/is_anagram/main.py
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
class Solution:
|
||||||
|
def isAnagram(self, s: str, t: str) -> bool:
|
||||||
|
s_chars = dict()
|
||||||
|
t_chars = dict()
|
||||||
|
for s_char in s:
|
||||||
|
new_char_check = s_chars.get(s_char)
|
||||||
|
if not new_char_check:
|
||||||
|
s_chars[s_char] = 1
|
||||||
|
else:
|
||||||
|
s_chars[s_char] += 1
|
||||||
|
for t_char in t:
|
||||||
|
new_char_check = t_chars.get(t_char)
|
||||||
|
if not new_char_check:
|
||||||
|
t_chars[t_char] = 1
|
||||||
|
else:
|
||||||
|
t_chars[t_char] += 1
|
||||||
|
return True if s_chars == t_chars else False
|
||||||
|
|
||||||
|
|
||||||
|
class NeetCodeSolution:
|
||||||
|
def isAnagram(self, s: str, t: str) -> bool:
|
||||||
|
if len(s) != len(t):
|
||||||
|
return False
|
||||||
|
|
||||||
|
countS, countT = {}, {}
|
||||||
|
|
||||||
|
for i in range(len(s)):
|
||||||
|
countS[s[i]] = 1 + countS.get(s[i], 0)
|
||||||
|
countT[t[i]] = 1 + countT.get(t[i], 0)
|
||||||
|
return countS == countT
|
||||||
|
|
||||||
|
|
||||||
|
entry_1 = {"s": "racecar", "t": "carrace", "expected": True}
|
||||||
|
entry_2 = {"s": "jar", "t": "jam", "expected": False}
|
||||||
|
# entry_3 = {"s": "racecar", "t": "carrace", "expected": True}
|
||||||
|
# entry_4 = {"s": "racecar", "t": "carrace", "expected": True}
|
||||||
|
# entry_5 = {"s": "racecar", "t": "carrace", "expected": True}
|
||||||
|
|
||||||
|
s = Solution()
|
||||||
|
print(s.isAnagram(entry_1["s"], entry_1["t"]))
|
||||||
|
print(s.isAnagram(entry_2["s"], entry_2["t"]))
|
0
neetcode/top_k_elems_in_list/__init__.py
Normal file
0
neetcode/top_k_elems_in_list/__init__.py
Normal file
21
neetcode/top_k_elems_in_list/main.py
Normal file
21
neetcode/top_k_elems_in_list/main.py
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
from collections import defaultdict
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
||||||
|
frequency_hashmap: Dict[int, int] = defaultdict(int)
|
||||||
|
result_hasmap: Dict[int, int] = defaultdict(int)
|
||||||
|
for nums_entry in nums:
|
||||||
|
frequency_hashmap[nums_entry] += 1
|
||||||
|
if not result_hasmap[frequency_hashmap[nums_entry]]:
|
||||||
|
result_hasmap[frequency_hashmap[nums_entry]] = nums_entry
|
||||||
|
return result_hasmap
|
||||||
|
# return list(result_hasmap.values())[-k:]
|
||||||
|
|
||||||
|
|
||||||
|
s = Solution()
|
||||||
|
# print(s.topKFrequent(nums=[1, 2, 2, 2, 5, 5, 5, 5, 3, 3, 3, 3, 3], k=2))
|
||||||
|
# print(s.topKFrequent(nums=[1, 2, 2, 3, 3, 3], k=2))
|
||||||
|
print(s.topKFrequent(nums=[1, 1, 1, 2, 2, 3], k=2))
|
||||||
|
# print(s.topKFrequent(nums=[7, 7], k=1))
|
0
neetcode/two_sums/__init__.py
Normal file
0
neetcode/two_sums/__init__.py
Normal file
26
neetcode/two_sums/main.py
Normal file
26
neetcode/two_sums/main.py
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||||
|
for i in range(0, len(nums)):
|
||||||
|
for j in range(i + 1, len(nums)):
|
||||||
|
if nums[i] + nums[j] == target:
|
||||||
|
return [i, j]
|
||||||
|
|
||||||
|
|
||||||
|
class NeetCodeSolution:
|
||||||
|
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||||
|
prevMap = {} # val -> index
|
||||||
|
|
||||||
|
for i, n in enumerate(nums):
|
||||||
|
diff = target - n
|
||||||
|
if diff in prevMap:
|
||||||
|
return [prevMap[diff], i]
|
||||||
|
prevMap[n] = i
|
||||||
|
|
||||||
|
|
||||||
|
s = Solution()
|
||||||
|
print(s.twoSum([3, 4, 5, 6, 7], 7))
|
||||||
|
print(s.twoSum([4, 5, 6], 10))
|
||||||
|
print(s.twoSum([5, 5], 10))
|
BIN
neetcode/two_sums/photo_2024-08-01_22-16-15.jpg
Normal file
BIN
neetcode/two_sums/photo_2024-08-01_22-16-15.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 78 KiB |
7
poetry.lock
generated
Normal file
7
poetry.lock
generated
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
# This file is automatically @generated by Poetry 1.4.2 and should not be changed by hand.
|
||||||
|
package = []
|
||||||
|
|
||||||
|
[metadata]
|
||||||
|
lock-version = "2.0"
|
||||||
|
python-versions = "^3.10"
|
||||||
|
content-hash = "53f2eabc9c26446fbcc00d348c47878e118afc2054778c3c803a0a8028af27d9"
|
17
power_of_two/c/power.c
Normal file
17
power_of_two/c/power.c
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
// Binary Search in C
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main(void)
|
||||||
|
{
|
||||||
|
int r = 0;
|
||||||
|
int test_array[] = {1,2,5};
|
||||||
|
int test_result[5];
|
||||||
|
int k = sizeof(test_array) / sizeof(test_array[0]);
|
||||||
|
for (int i = 1; i < k; i++) {
|
||||||
|
r = 10*r + test_array[i];
|
||||||
|
test_result[i]= r / 2;
|
||||||
|
r = r % 2;
|
||||||
|
printf("%d", test_result[i]);
|
||||||
|
}
|
||||||
|
}
|
17
power_of_two/python/negative_power.py
Normal file
17
power_of_two/python/negative_power.py
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
def calculate_negative_power_of_two(n: int):
|
||||||
|
result_array = []
|
||||||
|
for i in range(1, n):
|
||||||
|
result_array.append(i)
|
||||||
|
print(result_array)
|
||||||
|
for k in range(0, n - 1):
|
||||||
|
r = 0
|
||||||
|
print(".", end="")
|
||||||
|
for i in range(0, k):
|
||||||
|
r = 10 * r + result_array[i]
|
||||||
|
result_array[i] = r // 2
|
||||||
|
r = r % 2
|
||||||
|
print(result_array[i], end="")
|
||||||
|
result_array[k] = 5
|
||||||
|
print("5")
|
||||||
|
|
||||||
|
calculate_negative_power_of_two(20)
|
12
power_of_two/python/power.py
Normal file
12
power_of_two/python/power.py
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
if __name__ == "__main__":
|
||||||
|
input_array = [3, 1, 2, 5]
|
||||||
|
result_array = []
|
||||||
|
r = 0
|
||||||
|
for index, value in enumerate(input_array):
|
||||||
|
r = 10 * r + value
|
||||||
|
result_array.append(r // 2)
|
||||||
|
r = r % 2
|
||||||
|
if r != 0:
|
||||||
|
r = 10 * r
|
||||||
|
result_array.append(r//2)
|
||||||
|
print(result_array)
|
15
pyproject.toml
Normal file
15
pyproject.toml
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
[tool.poetry]
|
||||||
|
name = "algos-and-structures"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = ""
|
||||||
|
authors = ["pro100ton <pro100ton@gmail.com>"]
|
||||||
|
readme = "README.md"
|
||||||
|
packages = [{include = "algos_and_structures"}]
|
||||||
|
|
||||||
|
[tool.poetry.dependencies]
|
||||||
|
python = "^3.10"
|
||||||
|
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["poetry-core"]
|
||||||
|
build-backend = "poetry.core.masonry.api"
|
4
pyrightconfig.json
Normal file
4
pyrightconfig.json
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"venv": ".venv",
|
||||||
|
"venvPath": "/home/pro100ton/Documents/development/algos_and_structures"
|
||||||
|
}
|
Loading…
Reference in a new issue