From a5169c9b8532d3bac8cbe93ba73d28422b4192a0 Mon Sep 17 00:00:00 2001 From: "a.shalimov" Date: Sat, 7 Feb 2026 09:19:45 +0300 Subject: [PATCH] Update from work PC --- .../top_k_frequent_elements_optimal.py | 30 ++++++++++ algocode/hash_tables/valid_sudoku.py | 52 ++++++++++++++++ .../intersaction_of_sorted_arrays.py | 60 +++++++++++++++++++ .../unique_elements_in_two_arrays.py | 45 ++++++++++++++ algocode/two_pointers/valid_palindrome.py | 44 ++++++++++++++ 5 files changed, 231 insertions(+) create mode 100644 algocode/hash_tables/top_k_frequent_elements_optimal.py create mode 100644 algocode/hash_tables/valid_sudoku.py create mode 100644 algocode/two_pointers/intersaction_of_sorted_arrays.py create mode 100644 algocode/two_pointers/unique_elements_in_two_arrays.py create mode 100644 algocode/two_pointers/valid_palindrome.py diff --git a/algocode/hash_tables/top_k_frequent_elements_optimal.py b/algocode/hash_tables/top_k_frequent_elements_optimal.py new file mode 100644 index 0000000..c6013fd --- /dev/null +++ b/algocode/hash_tables/top_k_frequent_elements_optimal.py @@ -0,0 +1,30 @@ +from typing import List +from collections import defaultdict + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + res = [] + count_elems = defaultdict(int) + count_in = { i: set() for i in range(0, len(nums) + 1) } + for i in range(0, len(nums)): + cur_char = nums[i] + count_elems[cur_char] += 1 + tmp_value = count_elems[cur_char] + count_in[tmp_value].add(cur_char) + count_in[tmp_value - 1].discard(cur_char) + # Начинаем обход count_in с самого большого значения вхождений + for i in range(len(nums), 0, -1): + # Если есть элементы - записываем их в массив res + while len(count_in[i]) > 0: + res.append(count_in[i].pop()) + # Уменьшаем значение k + k -=1 + if k == 0: + return res + return res + +cl = Solution() +print(cl.topKFrequent(nums=[1,1,1,2,2,3], k = 2)) +print(cl.topKFrequent(nums=[1], k = 1)) +print(cl.topKFrequent(nums = [1,2,1,2,1,2,3,1,3,2], k = 2)) + diff --git a/algocode/hash_tables/valid_sudoku.py b/algocode/hash_tables/valid_sudoku.py new file mode 100644 index 0000000..5d6a4e1 --- /dev/null +++ b/algocode/hash_tables/valid_sudoku.py @@ -0,0 +1,52 @@ +from typing import List +from collections import defaultdict + + +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + rows = defaultdict(set) + cols = defaultdict(set) + sqrs = defaultdict(set) + for row_count in range(0, len(board)): + for col_count in range(0, len(board[row_count])): + elem = board[row_count][col_count] + if elem == ".": + continue + if elem in rows[row_count] or elem in cols[col_count] or elem in sqrs[(row_count//3, col_count//3)]: + return False + rows[row_count].add(elem) + cols[col_count].add(elem) + sqrs[(row_count//3, col_count//3)].add(elem) + col_count += 1 + row_count += 1 + return True + + +cl = Solution() +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"], +] +exp = True +print(f"Exp: {exp}\nRes: {cl.isValidSudoku(board)}") + +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"], +] +exp = False +print(f"Exp: {exp}\nRes: {cl.isValidSudoku(board)}") diff --git a/algocode/two_pointers/intersaction_of_sorted_arrays.py b/algocode/two_pointers/intersaction_of_sorted_arrays.py new file mode 100644 index 0000000..77262be --- /dev/null +++ b/algocode/two_pointers/intersaction_of_sorted_arrays.py @@ -0,0 +1,60 @@ +""" +Даны два отсортированных по возрастанию массива nums1 и nums2. Необходимо вернуть новый массив nums3, который содержит все общие элементы из nums1 и nums2. + +Результат должен быть также отсортирован по возрастанию. Если элементы встречаются в массивах несколько раз, то их нужно продублировать в ответе. + +Пример 1: + +Ввод: nums1 = [-3,2,2,5,8,19,31], nums2 = [1,2,2,2,6,19,52] +Вывод: [2,2,19] +Пример 2: + +Ввод: nums1 = [-5,4], nums2 = [1,2] +Вывод: [] +Пример 3: + +Ввод: nums1 = [], nums2 = [1,2] +Вывод: [] +Ограничения: + +len(nums1), len(nums2) >= 0 +""" + +from typing import List + + +def solve(nums1, nums2) -> List: + if len(nums1) == 0 or len(nums2) ==0: + return [] + res = [] + i, j = 0, 0 + while i < len(nums1): + if j >= len(nums2): + break + nums1_num = nums1[i] + nums2_num = nums2[j] + if nums1_num > nums2_num: + j +=1 + if nums1_num < nums2_num: + i +=1 + if nums1_num == nums2_num: + res.append(nums1[i]) + i+=1 + j+=1 + return res + + + +print(solve(nums1 = [-3,2,2,5,8,19,31], nums2 = [1,2,2,2,6,19,52])) +print([2,2,19]) +print("\n") + +print(solve(nums1 = [-5,4], nums2 = [1,2])) +print([]) +print("\n") + +print(solve(nums1 = [], nums2 = [1,2])) +print([]) +print("\n") + + diff --git a/algocode/two_pointers/unique_elements_in_two_arrays.py b/algocode/two_pointers/unique_elements_in_two_arrays.py new file mode 100644 index 0000000..00201c7 --- /dev/null +++ b/algocode/two_pointers/unique_elements_in_two_arrays.py @@ -0,0 +1,45 @@ +""" +Даны два массива nums1 и nums2, отсортированные по возрастанию и состоящие из уникальных элементов. Нужно найти все элементы, которые встречаются только в одном из массивов и вернуть их в порядке возрастания. + +Пример 1: + +Ввод: nums1 = [1,5,7,9], nums2 = [2,3,5,6,7,8] +Вывод: [1,2,3,6,8,9] +Пример 2: + +Ввод: nums1 = [2,3], nums2 = [1] +Вывод: [1,2,3] +Ограничения: + +len(nums1) + len(nums2) >= 1 +""" + +def solve(nums1, nums2): + res = [] + if len(nums1) > len(nums2): + short = nums2 + long = nums1 + else: + short = nums1 + long = nums2 + s, l = 0, 0 + while s < len(short): + if short[s] == long[l]: + l+=1 + s+=1 + elif short[s] < long[l]: + res.append(short[s]) + s+=1 + elif short[s] > long[l]: + + + return res + +s +1,5,7,9 +l +2,3,5,6,7,8 + + +[1,2,3,6,8,9] + diff --git a/algocode/two_pointers/valid_palindrome.py b/algocode/two_pointers/valid_palindrome.py new file mode 100644 index 0000000..5b629b6 --- /dev/null +++ b/algocode/two_pointers/valid_palindrome.py @@ -0,0 +1,44 @@ +""" +A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. +Alphanumeric characters include letters and numbers. + +Given a string s, return true if it is a palindrome, or false otherwise. + +Example 1: +Input: s = "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. + +Example 2: +Input: s = "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. + +Example 3: +Input: s = " " +Output: true +Explanation: s is an empty string "" after removing non-alphanumeric characters. +Since an empty string reads the same forward and backward, it is a palindrome. + +Constraints: + +1 <= s.length <= 2 * 105 +s consists only of printable ASCII characters. +""" + +""" +Инициализируем i - первый элемент (символ строки), j - последний +Далее будем каждый шаг двигать их к друг другу, пока i > j +По ходу будем: +1. Убеждаться что у нас действительная буква (не символы всякие по типу запятых, пробелов и т.д) + 1.1 Если попадается что-то не валидное - двигаем указатель дальше +2. Как только убедились что пришел валидный символ - делаем его lowercase +3. Срваниваем +A man, a plan, a canal: Panama +i j +""" + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return +