├── .gitignore ├── 121_ Best Time to Buy and Sell Stock └── solution.py ├── 125_Valid Palindrome ├── sol2.py └── solution.py ├── 136 Single Number └── solution.py ├── 13_Roman to Integer └── solution.py ├── 14 Longest Common Prefix └── solution.py ├── 1_TwoSum ├── solution.py └── solution1.py ├── 20 Valid Parentheses └── solution.py ├── 202 Happy Number └── solution.py ├── 21 Merge Two Sorted Lists └── solution.py ├── 26 Remove Duplicates from Sorted Array └── solution.py ├── 268 Missing Number └── solution.py ├── 2923_ Find Champion I └── solution.py ├── 292_Nim Game └── solution.py ├── 326 Power of Three └── solution.py ├── 392_Is Subsequence └── solution.py ├── 56 Merge Intervals └── solution.py ├── 564 Find the Closest Palindrome └── solution.py ├── 58 Length of Last Word └── solution.py ├── 66 Plus One └── solution.py ├── 724_ Find Pivot Index └── solution.py ├── 832_Flipping an Image └── solution.py ├── 88_Merge Sorted Array └── solution.py ├── 9_Palindrome Number ├── solution.py └── v2.py ├── RAG └── rag_schema.py ├── README.md ├── hacker_rank └── lc.py ├── internship.py ├── linked_list ├── linkedList_practise.py ├── linked_list.py ├── linked_list_exercise.ipynb ├── linkedlist.py └── v2_practise.py ├── missing_arr └── solution.py ├── pol_with_x.py ├── practice_small_code.ipynb ├── solution.py └── test_pose.py /.gitignore: -------------------------------------------------------------------------------- 1 | # .gitignore 2 | 3 | .idea/ 4 | 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .nox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | *.py,cover 57 | .hypothesis/ 58 | .pytest_cache/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # IPython 87 | profile_default/ 88 | ipython_config.py 89 | 90 | # pyenv 91 | .python-version 92 | 93 | # celery beat schedule file 94 | celerybeat-schedule 95 | 96 | # SageMath parsed files 97 | *.sage.py 98 | 99 | 100 | # Environments 101 | .env 102 | .venv 103 | env/ 104 | venv/ 105 | ENV/ 106 | env.bak/ 107 | venv.bak/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyder-py3 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | .dmypy.json 122 | dmypy.json 123 | 124 | # Pyre type checker 125 | .pyre/ -------------------------------------------------------------------------------- /121_ Best Time to Buy and Sell Stock/solution.py: -------------------------------------------------------------------------------- 1 | # 121. Best Time to Buy and Sell Stock 2 | # You are given an array prices where prices[i] is the price of a given stock on the ith day. 3 | # 4 | # You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 5 | # 6 | # Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 7 | # Input: prices = [7,1,5,3,6,4] 8 | # Output: 5 9 | # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 10 | # Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 11 | # 12 | 13 | 14 | def sellstock(prices): 15 | # counter = max(prices) 16 | # postocut = 0 17 | # price_to_buy = 0 18 | # for i in prices: 19 | # if i < counter: 20 | # counter = i 21 | # postocut = prices[i] 22 | # price_to_buy = i 23 | # 24 | # newlist = prices[postocut:] 25 | # max_val = max(newlist) 26 | # profit = max_val - price_to_buy 27 | # return profit 28 | 29 | # counter = max(prices) 30 | # postocut = min(prices) 31 | # pos = 0 32 | # for i, price in enumerate(prices): 33 | # if price == postocut: 34 | # pos = i 35 | # newlist = prices[pos:] 36 | # max_val = max(newlist) 37 | # profit = max_val - postocut 38 | # return profit 39 | 40 | #using 2 pointers approach 41 | max_profit = 0 42 | lenght_list = len(prices) 43 | pointer1 = 0 44 | pointer2 = 1 45 | 46 | while pointer2 < lenght_list: 47 | if prices[pointer1] > prices[pointer2]: 48 | pointer1 = pointer2 49 | 50 | else: 51 | check_profit = prices[pointer2] - prices[pointer1] 52 | if check_profit > max_profit: 53 | max_profit = check_profit 54 | pointer2 += 1 55 | 56 | 57 | return max_profit 58 | 59 | 60 | # prices = [7,1,5,3,6,4] 61 | # 62 | # prices = [7, 6, 4, 3, 1] 63 | 64 | prices = [2, 1, 4] 65 | 66 | #prices = [2, 4, 1] 67 | 68 | print(sellstock(prices)) 69 | -------------------------------------------------------------------------------- /125_Valid Palindrome/sol2.py: -------------------------------------------------------------------------------- 1 | # Input: s = "A man, a plan, a canal: Panama" 2 | # Output: true 3 | # Explanation: "amanaplanacanalpanama" is a palindrome. 4 | 5 | 6 | s = "A man, a plan, a canal: Panama" 7 | 8 | def pol(string): 9 | ar = '' 10 | 11 | for i in string: 12 | if i.isalpha() or i.isnumeric(): 13 | ar += i.lower() 14 | 15 | print(ar) 16 | 17 | po1, po2 = 0, len(ar) - 1 18 | 19 | while po1 < po2: 20 | if ar[po1] == ar[po2]: 21 | po1 += 1 22 | po2 -= 1 23 | else: 24 | return False 25 | return True 26 | 27 | 28 | print(pol(s)) -------------------------------------------------------------------------------- /125_Valid Palindrome/solution.py: -------------------------------------------------------------------------------- 1 | ###A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all 2 | # non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. 3 | # 4 | # Given a string s, return true if it is a palindrome, or false otherwise. 5 | # 6 | # 7 | # 8 | # Example 1: 9 | # 10 | # Input: s = "A man, a plan, a canal: Panama" 11 | # Output: true 12 | # Explanation: "amanaplanacanalpanama" is a palindrome. 13 | # Example 2: 14 | # 15 | # Input: s = "race a car" 16 | # Output: false 17 | # Explanation: "raceacar" is not a palindrome. 18 | # Example 3: 19 | # 20 | # Input: s = " " 21 | # Output: true 22 | # Explanation: s is an empty string "" after removing non-alphanumeric characters. 23 | # Since an empty string reads the same forward and backward, it is a palindrome. 24 | # 25 | 26 | 27 | s = "A man, a plan, a canal: Panama" 28 | 29 | def palindrome(s): 30 | string = '' 31 | 32 | for i in s: 33 | if i.isalpha() or i.isnumeric(): 34 | string += i.lower() 35 | 36 | 37 | left, right = 0, len(string) - 1 38 | 39 | while left < right: 40 | if string[left] == string[right]: 41 | left += 1 42 | right -= 1 43 | else: 44 | return False 45 | return True 46 | 47 | 48 | 49 | print(palindrome(s)) -------------------------------------------------------------------------------- /136 Single Number/solution.py: -------------------------------------------------------------------------------- 1 | # Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 2 | # 3 | # You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | 5 | # Example 1: 6 | # 7 | # Input: nums = [2,2,1] 8 | # Output: 1 9 | # Example 2: 10 | # 11 | # Input: nums = [4,1,2,1,2] 12 | # Output: 4 13 | # Example 3: 14 | # 15 | # Input: nums = [1] 16 | # Output: 1 17 | 18 | 19 | nums = [4, 1, 2, 1, 2] 20 | 21 | 22 | def checknums(nums) -> int: 23 | 24 | #dict style 25 | emtpy_dic = {} 26 | count = 0 27 | for i in nums: 28 | if i in emtpy_dic: 29 | emtpy_dic[i] += 1 30 | else: 31 | emtpy_dic[i] = 1 32 | # print(emtpy_dic) 33 | 34 | 35 | for k,v in emtpy_dic.items(): 36 | if v == 1: 37 | return k 38 | 39 | 40 | print(checknums(nums)) 41 | -------------------------------------------------------------------------------- /13_Roman to Integer/solution.py: -------------------------------------------------------------------------------- 1 | # Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 2 | # 3 | # Symbol Value 4 | # I 1 5 | # V 5 6 | # X 10 7 | # L 50 8 | # C 100 9 | # D 500 10 | # M 1000 11 | # For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. 12 | # 13 | # Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 14 | # 15 | # I can be placed before V (5) and X (10) to make 4 and 9. 16 | # X can be placed before L (50) and C (100) to make 40 and 90. 17 | # C can be placed before D (500) and M (1000) to make 400 and 900. 18 | # Given a roman numeral, convert it to an integer. 19 | # 20 | # 21 | # 22 | # Example 1: 23 | # 24 | # Input: s = "III" 25 | # Output: 3 26 | # Explanation: III = 3. 27 | # Example 2: 28 | # 29 | # Input: s = "LVIII" 30 | # Output: 58 31 | # Explanation: L = 50, V= 5, III = 3. 32 | # Example 3: 33 | # 34 | # Input: s = "MCMXCIV" 35 | # Output: 1994 36 | # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 37 | # 38 | 39 | s = "LII" 40 | 41 | greeksymbols = { 42 | "I": 1, 43 | "V": 5, 44 | "X": 10, 45 | "L": 50 46 | } 47 | 48 | 49 | def RtoI(s) -> int: 50 | listnumbers = [i for i in s] 51 | sum = 0 52 | pointer1, pointer2 = 0, 1 53 | 54 | for i in range(len(s) - 1): 55 | current_val = greeksymbols[listnumbers[pointer1]] 56 | next_val = greeksymbols[listnumbers[pointer2]] 57 | if current_val < next_val: 58 | sum -= current_val 59 | pointer1 += 1 60 | pointer2 += 1 61 | else: 62 | sum += current_val 63 | pointer1 += 1 64 | pointer2 += 1 65 | 66 | 67 | if pointer1 == len(listnumbers) - 1: 68 | sum += greeksymbols[listnumbers[pointer1]] 69 | 70 | return sum 71 | 72 | 73 | print(RtoI(s)) 74 | -------------------------------------------------------------------------------- /14 Longest Common Prefix/solution.py: -------------------------------------------------------------------------------- 1 | # Write a function to find the longest common prefix string amongst an array of strings. 2 | # 3 | # If there is no common prefix, return an empty string "". 4 | # 5 | # 6 | # 7 | # Example 1: 8 | # 9 | # Input: strs = ["flower","flow","flight"] 10 | # Output: "fl" 11 | # Example 2: 12 | # 13 | # Input: strs = ["dog","racecar","car"] 14 | # Output: "" 15 | # Explanation: There is no common prefix among the input strings. 16 | # 17 | # 18 | strs = ["flower", "flow", "floight"] 19 | 20 | 21 | # strs = ["dog","racecar","car"] 22 | 23 | def longest(strs) -> str: 24 | prefix = strs[0] #flower 25 | answer = "" 26 | po1 = 0 27 | 28 | for i in prefix: 29 | for j in range(1, len(strs)): 30 | if po1 >= len(strs[j]) or i != strs[j][po1]: 31 | return answer 32 | answer += i 33 | po1 += 1 34 | 35 | return answer 36 | 37 | 38 | print(longest(strs)) 39 | -------------------------------------------------------------------------------- /1_TwoSum/solution.py: -------------------------------------------------------------------------------- 1 | ###Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | 3 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | # 5 | # You can return the answer in any order. 6 | # Example 1: 7 | # 8 | # Input: nums = [2,7,11,15], target = 9 9 | # Output: [0,1] 10 | # Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | # Example 2: 12 | # 13 | # Input: nums = [3,2,4], target = 6 14 | # Output: [1,2] 15 | # Example 3: 16 | # 17 | # Input: nums = [3,3], target = 6 18 | # Output: [0,1] 19 | # 20 | 21 | 22 | nums = [2,7,11,15] 23 | target = 9 24 | 25 | 26 | def twosum(nums, target) -> list: 27 | storage = {} 28 | for i, num in enumerate(nums): 29 | if target - num in storage: 30 | return [storage[target - num], i] 31 | storage[num] = i 32 | 33 | 34 | print(twosum(nums=nums, target=target)) -------------------------------------------------------------------------------- /1_TwoSum/solution1.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | # 3 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | # 5 | # You can return the answer in any order. 6 | from typing import Tuple, Any 7 | 8 | nums = [2,7,11,15] 9 | target = 9 10 | 11 | def sum(nums, target) -> tuple[Any, Any]: 12 | 13 | # for i in range(len(nums)): 14 | # for j in range(i+1, len(nums)): 15 | # if nums[i] + nums[j] == target: 16 | # return i, j 17 | # 18 | # return -1, -1 19 | 20 | dict = {} 21 | 22 | for i, n in enumerate(nums): 23 | complement = target - n 24 | if complement in dict: 25 | return dict[complement], i 26 | dict[n] = i 27 | 28 | print(sum(nums, target)) 29 | 30 | -------------------------------------------------------------------------------- /20 Valid Parentheses/solution.py: -------------------------------------------------------------------------------- 1 | # Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | # 3 | # An input string is valid if: 4 | # 5 | # Open brackets must be closed by the same type of brackets. 6 | # Open brackets must be closed in the correct order. 7 | # Every close bracket has a corresponding open bracket of the same type. 8 | # 9 | # 10 | # Example 1: 11 | # 12 | # Input: s = "()" 13 | # 14 | # Output: true 15 | 16 | 17 | s = "([])" 18 | 19 | 20 | def main(s) -> bool: 21 | stor = { 22 | "]" : "[", 23 | "}" : "{", 24 | ")" : "(" 25 | } 26 | stack = [] 27 | 28 | 29 | 30 | 31 | print(main(s)) -------------------------------------------------------------------------------- /202 Happy Number/solution.py: -------------------------------------------------------------------------------- 1 | ###Write an algorithm to determine if a number n is happy. 2 | # 3 | # A happy number is a number defined by the following process: 4 | # 5 | # Starting with any positive integer, replace the number by the sum of the squares of its digits. 6 | # Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 7 | # Those numbers for which this process ends in 1 are happy. 8 | # Return true if n is a happy number, and false if not. 9 | # 10 | # 11 | # 12 | # Example 1: 13 | # 14 | # Input: n = 19 15 | # Output: true 16 | # Explanation: 17 | # 12 + 92 = 82 18 | # 82 + 22 = 68 19 | # 62 + 82 = 100 20 | # 12 + 02 + 02 = 1 21 | 22 | 23 | n = 18 24 | 25 | def happynumber(n) -> bool: 26 | seen = set() 27 | 28 | while n != 1 and n not in seen: 29 | seen.add(n) 30 | n = sum(int(i) ** 2 for i in str(n)) 31 | 32 | return n == 1 33 | 34 | 35 | 36 | # if result == 1 -- > return True 37 | 38 | 39 | print(happynumber(n)) 40 | 41 | 42 | -------------------------------------------------------------------------------- /21 Merge Two Sorted Lists/solution.py: -------------------------------------------------------------------------------- 1 | # 21. Merge Two Sorted Lists 2 | # You are given the heads of two sorted linked lists list1 and list2. 3 | # 4 | # Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. 5 | # 6 | # Return the head of the merged linked list. 7 | # 8 | # Input: list1 = [1,2,4], list2 = [1,3,4] 9 | # Output: [1,1,2,3,4,4] 10 | # Example 2: 11 | # 12 | # Input: list1 = [], list2 = [] 13 | # Output: [] 14 | # Example 3: 15 | # 16 | # Input: list1 = [], list2 = [0] 17 | # Output: [0] 18 | # 19 | 20 | list1, list2 = [1, 2, 4], [1, 3, 4] 21 | 22 | 23 | def merge2list(list1, list2) -> list: 24 | final_list = [] 25 | po1, po2 = 0, 0 26 | itter = 0 27 | lenght = (len(list1) + len(list2)) 28 | 29 | while itter < lenght: 30 | if po1 == len(list1): 31 | final_list.append(list2[po2]) 32 | po2 += 1 33 | itter += 1 34 | elif po2 == len(list2): 35 | final_list.append(list1[po1]) 36 | po1 += 1 37 | itter += 1 38 | 39 | elif list1[po1] <= list2[po2]: 40 | final_list.append(list1[po1]) 41 | po1 += 1 42 | itter += 1 43 | else: 44 | if list1[po1] > list2[po2]: 45 | final_list.append(list2[po2]) 46 | po2 += 1 47 | itter += 1 48 | 49 | return final_list 50 | 51 | 52 | print(merge2list(list1, list2)) 53 | -------------------------------------------------------------------------------- /26 Remove Duplicates from Sorted Array/solution.py: -------------------------------------------------------------------------------- 1 | # 26. Remove Duplicates from Sorted Array 2 | # https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 3 | 4 | nums = [0,0,1,1,1,2,2,3,3,4] 5 | 6 | # nums = [1,2] 7 | def duplicate(nums): 8 | if len(nums) <= 1: 9 | return len(nums) 10 | 11 | po1 = 1 12 | 13 | for po2 in range(1, len(nums)): 14 | if nums[po2] != nums[po2 - 1]: 15 | nums[po1] = nums[po2] 16 | po1 += 1 17 | 18 | return po1 19 | 20 | 21 | print(duplicate(nums)) -------------------------------------------------------------------------------- /268 Missing Number/solution.py: -------------------------------------------------------------------------------- 1 | # Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. 2 | # 3 | # 4 | # 5 | # Example 1: 6 | # 7 | # Input: nums = [3,0,1] 8 | # Output: 2 9 | # Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. 10 | 11 | 12 | nums = [3, 0, 1] 13 | 14 | def missingnum(nums) -> int: 15 | 16 | list1 = [] 17 | 18 | for i in range(0, len(nums)+1): 19 | list1.append(i) 20 | # print(list1) 21 | 22 | for i in list1: 23 | if i not in nums: 24 | return i 25 | 26 | 27 | print(missingnum(nums)) -------------------------------------------------------------------------------- /2923_ Find Champion I/solution.py: -------------------------------------------------------------------------------- 1 | # 2923. Find Champion I 2 | # Easy 3 | # Topics 4 | # Companies 5 | # Hint 6 | # There are n teams numbered from 0 to n - 1 in a tournament. 7 | # 8 | # Given a 0-indexed 2D boolean matrix grid of size n * n. For all i, j that 0 <= i, j <= n - 1 and i != j team i is stronger than team j if grid[i][j] == 1, otherwise, team j is stronger than team i. 9 | # Team a will be the champion of the tournament if there is no team b that is stronger than team a. 10 | # 11 | # Return the team that will be the champion of the tournament. 12 | # Example 1: 13 | # 14 | # Input: grid = [[0,1],[0,0]] 15 | # Output: 0 16 | # Explanation: There are two teams in this tournament. 17 | # grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion. 18 | # Example 2: 19 | # 20 | # Input: grid = [[0,0,1],[1,0,1],[0,0,0]] 21 | # Output: 1 22 | # Explanation: There are three teams in this tournament. 23 | # grid[1][0] == 1 means that team 1 is stronger than team 0. 24 | # grid[1][2] == 1 means that team 1 is stronger than team 2. 25 | # So team 1 will be the champion. 26 | 27 | grid = [[0,1],[0,0]] 28 | 29 | def winner(grid) -> int: 30 | ... 31 | 32 | 33 | 34 | winner(grid) -------------------------------------------------------------------------------- /292_Nim Game/solution.py: -------------------------------------------------------------------------------- 1 | # You are playing the following Nim Game with your friend: 2 | # 3 | # Initially, there is a heap of stones on the table. 4 | # You and your friend will alternate taking turns, and you go first. 5 | # On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. 6 | # The one who removes the last stone is the winner. 7 | # Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false. 8 | # 9 | # 10 | # 11 | # Example 1: 12 | # Input: n = 4 13 | # Output: false 14 | # Explanation: These are the possible outcomes: 15 | # 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 16 | # 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 17 | # 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. 18 | # In all outcomes, your friend wins. 19 | # 20 | # Example 2: 21 | # Input: n = 1 22 | # Output: true 23 | 24 | # Example 3: 25 | # Input: n = 2 26 | # Output: true 27 | 28 | 29 | n = 5 30 | 31 | 32 | def game(n): 33 | while True: 34 | if n % 4 == 0: 35 | return False 36 | else: 37 | return True 38 | 39 | 40 | print(game(n)) 41 | -------------------------------------------------------------------------------- /326 Power of Three/solution.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return true if it is a power of three. Otherwise, return false. 2 | # 3 | # An integer n is a power of three, if there exists an integer x such that n == 3x. 4 | # 5 | # 6 | # 7 | # Example 1: 8 | # 9 | # Input: n = 27 10 | # Output: true 11 | # Explanation: 27 = 33 12 | # Example 2: 13 | # 14 | # Input: n = 0 15 | # Output: false 16 | # Explanation: There is no x where 3x = 0. 17 | # Example 3: 18 | # 19 | # Input: n = -1 20 | # Output: false 21 | # Explanation: There is no x where 3x = (-1). 22 | 23 | 24 | n = 27 25 | 26 | def power(n) -> bool: 27 | 28 | if n <= 0: 29 | return False 30 | 31 | while n != 1: 32 | if n % 3 == 0: 33 | n = n // 3 34 | elif n % 3 != 0: 35 | return False 36 | 37 | return True 38 | 39 | 40 | 41 | 42 | print(power(n)) -------------------------------------------------------------------------------- /392_Is Subsequence/solution.py: -------------------------------------------------------------------------------- 1 | # Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 2 | # 3 | # A subsequence of a string is a new string that is formed from the original string by deleting some 4 | # (can be none) of the characters without disturbing the relative positions of the remaining characters. 5 | # (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 6 | # 7 | # 8 | # 9 | # Example 1: 10 | # 11 | # Input: s = "abc", t = "ahbgdc" 12 | # Output: true 13 | # Example 2: 14 | # 15 | # Input: s = "axc", t = "ahbgdc" 16 | # Output: false 17 | # 18 | s, t = "bb", "ahbgcd" 19 | 20 | 21 | def check(s, t) -> bool: 22 | list1 = [i for i in s] # b g 23 | list2 = [i for i in t] # a h b g c d 24 | 25 | po1, po2 = 0, 0 26 | 27 | while po1 < len(s) and po2 < len(t): 28 | if list1[po1] == list2[po2]: 29 | po1 += 1 30 | po2 += 1 31 | 32 | return po1 == len(list1) 33 | 34 | 35 | print(check(s, t)) 36 | -------------------------------------------------------------------------------- /56 Merge Intervals/solution.py: -------------------------------------------------------------------------------- 1 | #Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. 2 | 3 | intervals = [[1,4],[2,3]] 4 | 5 | 6 | def merge(intervals) -> list: 7 | answer = [] 8 | sorted_int = sorted(intervals) 9 | 10 | for i in sorted_int: 11 | if not answer: 12 | answer.append(i) 13 | 14 | if answer[-1][1] >= i[0]: 15 | answer[-1] = [answer[-1][0], max(answer[-1][1], i[1])] 16 | else: 17 | answer.append(i) 18 | 19 | return answer 20 | 21 | 22 | print(merge(intervals)) -------------------------------------------------------------------------------- /564 Find the Closest Palindrome/solution.py: -------------------------------------------------------------------------------- 1 | # Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. 2 | # 3 | # The closest is defined as the absolute difference minimized between two integers. 4 | # 5 | # 6 | # 7 | # Example 1: 8 | #Input: n = "123" 9 | #Output: "121" 10 | 11 | # need to find 2 polindromes first 12 | # return max(save(pol1, pol2)) 13 | 14 | n = '120' # output 121 15 | 16 | def forward_cheking(x) -> int: 17 | 18 | while True : 19 | number_to_check = int(x) + 1 20 | number = [i for i in str(number_to_check)] 21 | po1, po2 = 0, len(number) - 1 22 | 23 | while po1 < po2: 24 | 25 | if number[po1] == number[po2]: 26 | po1 +=1 27 | po2 -=1 28 | else: 29 | number_to_check +=1 30 | number = [i for i in str(number_to_check)] 31 | po1, po2 = 0, len(number) - 1 32 | 33 | 34 | return number_to_check 35 | 36 | 37 | def backward_cheking(x) -> int: 38 | 39 | while True : 40 | number_to_check = int(x) - 1 41 | number = [i for i in str(number_to_check)] 42 | po1, po2 = 0, len(number) - 1 43 | 44 | while po1 < po2: 45 | 46 | if number[po1] == number[po2]: 47 | po1 +=1 48 | po2 -=1 49 | else: 50 | number_to_check -=1 51 | number = [i for i in str(number_to_check)] 52 | po1, po2 = 0, len(number) - 1 53 | 54 | 55 | return number_to_check 56 | 57 | 58 | def nearestPalindromic(n: str) -> str: 59 | if int(n) < 0: 60 | return '0' 61 | elif 0 < int(n) < 10: 62 | return str(int(n) - 1) 63 | elif int(n) == 10 or int(n) == 11: 64 | return '9' 65 | 66 | forward_palindrome = forward_cheking(n) 67 | backward_palindrome = backward_cheking(n) 68 | 69 | if abs(forward_palindrome - int(n)) == abs(int(n) - backward_palindrome): 70 | return str(min(forward_palindrome, backward_palindrome)) 71 | elif abs(forward_palindrome - int(n)) < abs(int(n) - backward_palindrome): 72 | return str(forward_palindrome) 73 | else: 74 | return str(backward_palindrome) 75 | 76 | nearestPalindromic(n) -------------------------------------------------------------------------------- /58 Length of Last Word/solution.py: -------------------------------------------------------------------------------- 1 | # Given a string s consisting of words and spaces, return the length of the last word in the string. 2 | # 3 | # A word is a maximal 4 | # substring 5 | # consisting of non-space characters only. 6 | # 7 | # Example 1: 8 | # 9 | # Input: s = "Hello World" 10 | # Output: 5 11 | # Explanation: The last word is "World" with length 5. 12 | # Example 2: 13 | # 14 | # Input: s = " fly me to the moon " 15 | # Output: 4 16 | # Explanation: The last word is "moon" with length 4. 17 | # Example 3: 18 | # 19 | # Input: s = "luffy is still joyboy" 20 | # Output: 6 21 | # Explanation: The last word is "joyboy" with length 6. 22 | # 23 | 24 | s = " fly me to the moon " 25 | 26 | def func(s) -> int: 27 | lis = s.split(" ") 28 | final_list = [] 29 | 30 | for i in lis: 31 | if i.isalpha(): 32 | final_list.append(i) 33 | 34 | return len(final_list[-1]) 35 | 36 | 37 | print(func(s)) -------------------------------------------------------------------------------- /66 Plus One/solution.py: -------------------------------------------------------------------------------- 1 | # You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. 2 | # 3 | # Increment the large integer by one and return the resulting array of digits. 4 | # 5 | # 6 | # 7 | # Example 1: 8 | # 9 | # Input: digits = [1,2,3] 10 | # Output: [1,2,4] 11 | # Explanation: The array represents the integer 123. 12 | # Incrementing by one gives 123 + 1 = 124. 13 | # Thus, the result should be [1,2,4]. 14 | 15 | digits = [9, 9, 9] 16 | 17 | 18 | def plusone(digits) -> []: 19 | # st = "" 20 | # for i in digits: 21 | # st += str(i) 22 | # answer = int(st) + 1 23 | # answer1 = [int(i) for i in str(answer)] 24 | # return answer1 25 | 26 | digits.reverse() 27 | 28 | one, i = 1, 0 29 | 30 | while one: 31 | if i < len(digits): 32 | if digits[i] == 9: 33 | digits[i] = 0 34 | else: 35 | digits[i] += 1 36 | one = 0 37 | 38 | else: 39 | digits.append(1) 40 | one = 0 41 | 42 | i += 1 43 | 44 | return digits[::-1] 45 | 46 | print(plusone(digits)) 47 | -------------------------------------------------------------------------------- /724_ Find Pivot Index/solution.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers nums, calculate the pivot index of this array. 2 | # 3 | # The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. 4 | # 5 | # If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. 6 | # 7 | # Return the leftmost pivot index. If no such index exists, return -1. 8 | 9 | 10 | nums = [1,7,3,6,5,6] 11 | 12 | def pivot(nums) -> int: 13 | l, r = 0, len(nums) - 1 14 | l1, r1 = nums[l], nums[r] 15 | 16 | while l < r: 17 | if l1 < r1: 18 | l += 1 19 | l1 += nums[l] 20 | else: 21 | r -= 1 22 | r1 += nums[r] 23 | 24 | 25 | if l1 == r1: 26 | return l 27 | 28 | return -1 29 | 30 | 31 | print(pivot(nums)) -------------------------------------------------------------------------------- /832_Flipping an Image/solution.py: -------------------------------------------------------------------------------- 1 | #Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. 2 | # 3 | # To flip an image horizontally means that each row of the image is reversed. 4 | # 5 | # For example, flipping [1,1,0] horizontally results in [0,1,1]. 6 | # To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. 7 | # 8 | # For example, inverting [0,1,1] results in [1,0,0]. 9 | # 10 | # 11 | # Example 1: 12 | # 13 | # Input: image = [[1,1,0],[1,0,1],[0,0,0]] 14 | # Output: [[1,0,0],[0,1,0],[1,1,1]] 15 | # Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. 16 | # Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] 17 | # Example 2: 18 | # 19 | # Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 20 | # Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 21 | # Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 22 | # Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 23 | 24 | 25 | image = [[1,1,0],[1,0,1],[0,0,0]] 26 | 27 | def fliping_image(image): 28 | for i in image: 29 | i.reverse() 30 | return image 31 | 32 | def invert_image(image): 33 | for i in range(len(image)): 34 | for j in range(len(image[i])): 35 | image[i][j] = 1 - image[i][j] 36 | 37 | return image 38 | 39 | 40 | flip = fliping_image(image) 41 | 42 | print(invert_image(flip)) -------------------------------------------------------------------------------- /88_Merge Sorted Array/solution.py: -------------------------------------------------------------------------------- 1 | # 88. Merge Sorted Array 2 | # You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing 3 | # the number of elements in nums1 and nums2 respectively. 4 | # 5 | # Merge nums1 and nums2 into a single array sorted in non-decreasing order. 6 | # 7 | # The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate 8 | # this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are 9 | # set to 0 and should be ignored. nums2 has a length of n. 10 | # 11 | 12 | # class Solution: 13 | # def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 14 | # """ 15 | # Do not return anything, modify nums1 in-place instead. 16 | # """ 17 | # 18 | # 19 | # 20 | # 21 | # Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 22 | # Output: [1,2,2,3,5,6] 23 | # Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. 24 | # The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. 25 | # 26 | 27 | 28 | # def sortedarr(nums1, nums2, m, n): 29 | # nums1 += nums2 30 | # nums1.sort(reverse=True) 31 | # number = m + n 32 | # nums3 = nums1[0:number] 33 | # nums1 = nums3 34 | # nums1.sort() 35 | # print(nums1) 36 | # 37 | # 38 | # 39 | # nums1, nums2, m, n = [1,2,3,0,0,0], [2,5,6], 3, 3 40 | # 41 | # sortedarr 42 | 43 | # 123000 44 | # 256 45 | 46 | # 47 | # def sorted(nums1, nums2, m, n): 48 | # pointer1 = m - 1 49 | # pointer2 = n - 1 50 | # pointer = m + n - 1 51 | # 52 | # while pointer2 >= 0: 53 | # if nums2[pointer2] > nums1[pointer1]: 54 | # nums1[pointer] = nums2[pointer2] 55 | # pointer2 -= 1 56 | # elif nums1[pointer1] >= nums2[pointer2]: 57 | # nums1[pointer] = nums1[pointer1] 58 | # pointer1 -= 1 59 | # else: 60 | # nums1[pointer] = nums2[pointer2] 61 | # pointer2 -= 1 62 | # pointer -= 1 63 | # 64 | # print(nums1) 65 | # 66 | # 67 | # nums1, nums2, m, n = [1, 2, 3, 0, 0, 0], [2, 5, 6], 3, 3 68 | # 69 | # sorted(nums1, nums2, m, n) 70 | 71 | 72 | ### leetcode with class final solution 73 | 74 | class Solution: 75 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 76 | """ 77 | Do not return anything, modify nums1 in-place instead. 78 | """ 79 | pointer1 = m - 1 80 | pointer2 = n - 1 81 | pointer = m + n - 1 82 | 83 | while pointer2 >= 0: 84 | if nums2[pointer2] > nums1[pointer1] and pointer1 > 0: 85 | nums1[pointer] = nums2[pointer2] 86 | pointer2 -= 1 87 | elif nums1[pointer1] >= nums2[pointer2] and pointer1 >= 0: 88 | nums1[pointer] = nums1[pointer1] 89 | pointer1 -= 1 90 | else: 91 | nums1[pointer] = nums2[pointer2] 92 | pointer2 -= 1 93 | pointer -= 1 94 | -------------------------------------------------------------------------------- /9_Palindrome Number/solution.py: -------------------------------------------------------------------------------- 1 | #Given an integer x, return true if x is a 2 | # palindrome 3 | # , and false otherwise. 4 | # Example 1: 5 | # 6 | # Input: x = 121 7 | # Output: true 8 | # Explanation: 121 reads as 121 from left to right and from right to left. 9 | # Example 2: 10 | # 11 | # Input: x = -121 12 | # Output: false 13 | # Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 14 | # Example 3: 15 | # 16 | # Input: x = 10 17 | # Output: false 18 | # Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 19 | # 20 | 21 | x = 121 22 | 23 | 24 | def a(number) -> bool: 25 | linum = [i for i in str(number)] 26 | 27 | left, right = 0, len(linum) - 1 28 | 29 | while left < right: 30 | if linum[left] == linum[right]: 31 | left += 1 32 | right -= 1 33 | 34 | else: 35 | return False 36 | 37 | return True 38 | 39 | 40 | print(a(x)) 41 | -------------------------------------------------------------------------------- /9_Palindrome Number/v2.py: -------------------------------------------------------------------------------- 1 | #Example 1: 2 | # 3 | # Input: x = 121 4 | # Output: true 5 | # Explanation: 121 reads as 121 from left to right and from right to left. 6 | # Example 2: 7 | 8 | x = 121 9 | 10 | 11 | 12 | def polindrome(number) -> bool: 13 | if number < 0: 14 | return False 15 | elif 0 < number < 10: 16 | return False 17 | 18 | l_number = [i for i in str(number)] 19 | 20 | 21 | po1, po2 = 0, len(l_number) - 1 22 | 23 | while po1 < po2: 24 | if l_number[po1] == l_number[po2]: 25 | po1 +=1 26 | po2 -=1 27 | else: 28 | return False 29 | return True 30 | 31 | 32 | print(polindrome(x)) -------------------------------------------------------------------------------- /RAG/rag_schema.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.patches as mpatches 3 | 4 | # Create figure and axis 5 | fig, ax = plt.subplots(figsize=(10, 8)) 6 | 7 | # Remove the axis 8 | ax.axis('off') 9 | 10 | # Define box properties 11 | box_style = dict(boxstyle="round,pad=0.3", edgecolor="black", facecolor="lightblue") 12 | 13 | # Define the positions of the boxes 14 | positions = { 15 | "User Query": (0.5, 0.9), 16 | "Retriever": (0.5, 0.75), 17 | "Retriever Embeds Query": (0.5, 0.6), 18 | "Search Documents/Chunks": (0.5, 0.45), 19 | "Retrieve Top-K Relevant Chunks": (0.5, 0.3), 20 | "Pass Chunks to Generator": (0.5, 0.15), 21 | "Generate Final Response": (0.5, 0.05) 22 | } 23 | 24 | # Create the boxes 25 | for text, pos in positions.items(): 26 | ax.text(pos[0], pos[1], text, ha="center", va="center", bbox=box_style, fontsize=12) 27 | 28 | # Create the arrows 29 | arrow_props = dict(facecolor='black', shrink=0.05) 30 | for i in range(len(positions) - 1): 31 | start_pos = list(positions.values())[i] 32 | end_pos = list(positions.values())[i + 1] 33 | ax.annotate('', xy=end_pos, xytext=start_pos, arrowprops=dict(arrowstyle="->", lw=1.5)) 34 | 35 | # Display the flowchart 36 | plt.title("Flowchart for RAG Model", fontsize=14) 37 | plt.show() 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | 3 | This repository contains my practice solutions for LeetCode problems. Each solution is implemented in Python and organized by problem number, following the same order as LeetCode. 4 | 5 | ## Description 6 | 7 | This repository is dedicated to my personal practice and contains my solutions to various LeetCode problems. It serves as a learning resource for me and for anyone who is interested in understanding different ways to solve coding problems. 8 | 9 | ## Installation 10 | 11 | To run the solutions, ensure you have the latest version of Python installed. You can download it from [python.org](https://www.python.org/). 12 | 13 | ## Usage 14 | 15 | Each problem is stored in its own directory within the `leetcode` directory. You can navigate to the specific problem's directory and run the solution using Python. For example: 16 | 17 | ```bash 18 | cd leetcode/1.TwoSum 19 | python solution.py 20 | ``` 21 | 22 | ## Contributing 23 | 24 | Contributions are welcome! If you have an alternative solution or an improvement to an existing solution, feel free to contribute. Follow these steps: 25 | 26 | 1. Fork the repository. 27 | 2. Create a new branch (git checkout -b feature-new-solution). 28 | 3. Commit your changes (git commit -m 'Add new solution for problem X'). 29 | 4. Push to the branch (git push origin feature-new-solution). 30 | 5. Open a pull request. 31 | 32 | ## Structure 33 | 34 | The solutions are organized numerically by problem number and name, corresponding to their problem number on LeetCode. For example: 35 | 36 | ``` 37 | leetcode/ 38 | ├── 1_TwoSum/ 39 | │ └── solution.py 40 | ├── 2_AddTwoNumbers/ 41 | │ └── solution.py 42 | ``` 43 | 44 | ## Contact 45 | 46 | GitHub: [OfficialCodeVoyage](https://github.com/OfficialCodeVoyage) 47 | 48 | LinkedIn: [Pavlo Bondarenko](https://www.linkedin.com/in/mrbondarenko/) 49 | 50 | ## Acknowledgments 51 | 52 | Thank you to LeetCode for providing a platform to practice coding problems and improve problem-solving skills. 53 | 54 | -------------------------------------------------------------------------------- /hacker_rank/lc.py: -------------------------------------------------------------------------------- 1 | # ###1 2 | # if __name__ == '__main__': 3 | # # x = int(input()) 4 | # # y = int(input()) 5 | # # z = int(input()) 6 | # # n = int(input()) 7 | # 8 | # ## all cases 9 | # def all_cases(x=1, y=1, z=2) -> []: 10 | # all_cases = [] 11 | # 12 | # cases = [[i,j,k] for i in range(0,x+1) for j in range(0, y+1) for k in range(0,z+1)] 13 | # return cases 14 | # 15 | # 16 | # ## cases where it's not equal to n 17 | # 18 | # def equal_cases(cases, n=3): 19 | # equal_cases = [i for i in cases if i[1]+i[2]+i[0]==n] 20 | # 21 | # 22 | # return equal_cases 23 | # 24 | # 25 | # # print(equal_cases(all_cases(x, y, z), 3)) 26 | # print(equal_cases(all_cases())) 27 | 28 | #2 second lowest 29 | 30 | 31 | # students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] 32 | # 33 | # 34 | # ### need to print second lowest, if there are 2 grades print them alphabetically 35 | # 36 | # highest = students[0][1] 37 | # runner = float('inf') 38 | # 39 | # for i in range(1, len(students)): 40 | # if students[i][1] < highest: 41 | # runner = highest 42 | # highest = students[i][1] 43 | # elif students[i][1] < runner and students[i][1] != highest: 44 | # runner = students[i][1] 45 | # 46 | # print(runner) 47 | # 48 | # selected = [i for i in range(0,len(students)) if students[i][1] == runner] 49 | # ready = [] 50 | # 51 | # for i in selected: 52 | # ready.append(students[i]) 53 | # 54 | # ready.sort() 55 | # 56 | # 57 | # 58 | # 59 | 60 | ###3 61 | 62 | string = 'Banana' 63 | vowels = ['a', 'e', 'i', 'o', 'u'] 64 | consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] 65 | 66 | 67 | 68 | def count_stuart(string): 69 | words = [] 70 | 71 | for po1 in range(len(string)): 72 | if string[po1].lower() in consonants: 73 | for po2 in range(po1 + 1, len(string)+ 1): 74 | words.append(string[po1:po2]) 75 | 76 | score_dict = {word : words.count(word) for word in words} 77 | total_points = 0 78 | 79 | for k,v in score_dict.items(): 80 | total_points += v 81 | 82 | return total_points 83 | 84 | def count_kevin(string): 85 | words = [] 86 | 87 | for po1 in range(len(string)): 88 | if string[po1].lower() in vowels: 89 | for po2 in range(po1 + 1, len(string) + 1): 90 | words.append(string[po1:po2]) 91 | 92 | score_dict = {word: words.count(word) for word in words} 93 | total_points = 0 94 | 95 | for k, v in score_dict.items(): 96 | total_points += v 97 | 98 | return total_points 99 | 100 | def minion_game(string) -> str: 101 | kevin = count_kevin(string) 102 | stuart = count_stuart(string) 103 | result = '' 104 | if kevin > stuart: 105 | result = f'Kevin {kevin}' 106 | elif stuart > kevin: 107 | result = f'Stuart {stuart}' 108 | else: 109 | result = 'Draw' 110 | 111 | return result 112 | 113 | 114 | print(minion_game(string)) 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /internship.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficialCodeVoyage/leetcode/38383e37fa996479a321f1e6a7d2e8b2fee73b2d/internship.py -------------------------------------------------------------------------------- /linked_list/linkedList_practise.py: -------------------------------------------------------------------------------- 1 | # singly linked list 2 | from turtledemo.penrose import start 3 | 4 | 5 | class Node: 6 | def __init__(self, data): 7 | self.data = data 8 | self.next = None 9 | 10 | class LinkedList: 11 | def __init__(self): 12 | self.head = None 13 | 14 | def insertion_at_the_beginning(self, data): 15 | new_node = Node(data) 16 | new_node.next = self.head 17 | self.head = new_node 18 | 19 | def insertion_at_the_end(self, data): 20 | new_node = Node(data) 21 | 22 | if not self.head: 23 | self.head = new_node 24 | return 25 | 26 | last_checked = self.head 27 | 28 | while last_checked.next: 29 | last_checked = last_checked.next 30 | 31 | last_checked.next = new_node 32 | 33 | 34 | 35 | def printing_list(self): 36 | if not self.head: 37 | print("LList is empty") 38 | return 39 | 40 | current_read = self.head 41 | while current_read: 42 | print(current_read.data, end=" -> ") 43 | current_read = current_read.next 44 | print("None") 45 | 46 | 47 | 48 | 49 | llist = LinkedList() 50 | 51 | llist.printing_list() 52 | llist.insertion_at_the_beginning(1) 53 | llist.insertion_at_the_end(10) 54 | llist.insertion_at_the_beginning(12) 55 | llist.printing_list() 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /linked_list/linked_list.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None # Reference to the next node 5 | # LinkedList class manages the nodes and operations of the linked list 6 | class LinkedList: 7 | def __init__(self): 8 | self.head = None # Initialize an empty linked list 9 | def append(self, data): 10 | new_node = Node(data) 11 | if not self.head: 12 | self.head = new_node 13 | return 14 | last_node = self.head 15 | while last_node.next: 16 | last_node = last_node.next 17 | last_node.next = new_node 18 | def print_list(self): 19 | current_node = self.head 20 | while current_node: 21 | print(current_node.data, end=" -> ") 22 | current_node = current_node.next 23 | print("None") 24 | # Example usage: 25 | llist = LinkedList() 26 | llist.append(1) 27 | llist.append(2) 28 | llist.append(3) 29 | llist.print_list() -------------------------------------------------------------------------------- /linked_list/linked_list_exercise.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "metadata": {}, 5 | "cell_type": "markdown", 6 | "source": "Sinlgy Linked List", 7 | "id": "c0123aea81612f14" 8 | }, 9 | { 10 | "metadata": {}, 11 | "cell_type": "code", 12 | "outputs": [], 13 | "execution_count": null, 14 | "source": [ 15 | "class Node:\n", 16 | " def __init__(self, data):\n", 17 | " self.Data = data\n", 18 | " self.Next = None" 19 | ], 20 | "id": "bc64ebb2d3518d77" 21 | }, 22 | { 23 | "metadata": {}, 24 | "cell_type": "code", 25 | "outputs": [], 26 | "execution_count": null, 27 | "source": [ 28 | "class linkedList():\n", 29 | " def __int__(self, data):\n", 30 | " self.head = None\n", 31 | " \n", 32 | " \n", 33 | " " 34 | ], 35 | "id": "acdd448697aa318a" 36 | }, 37 | { 38 | "metadata": {}, 39 | "cell_type": "code", 40 | "outputs": [], 41 | "execution_count": null, 42 | "source": [ 43 | "llist = linkedList()\n", 44 | "llist()" 45 | ], 46 | "id": "ca8cb218d2f9d630" 47 | } 48 | ], 49 | "metadata": { 50 | "kernelspec": { 51 | "display_name": "Python 3", 52 | "language": "python", 53 | "name": "python3" 54 | }, 55 | "language_info": { 56 | "codemirror_mode": { 57 | "name": "ipython", 58 | "version": 2 59 | }, 60 | "file_extension": ".py", 61 | "mimetype": "text/x-python", 62 | "name": "python", 63 | "nbconvert_exporter": "python", 64 | "pygments_lexer": "ipython2", 65 | "version": "2.7.6" 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 5 70 | } 71 | -------------------------------------------------------------------------------- /linked_list/linkedlist.py: -------------------------------------------------------------------------------- 1 | from debugpy.common.timestamp import current 2 | 3 | 4 | class Node: 5 | def __init__(self, hold_value): 6 | 7 | self.data = hold_value ##Data field 8 | self.next = None ##next mode 9 | 10 | class LinkedList: 11 | def __init__(self): 12 | self.head = None 13 | 14 | def append(self, data): 15 | new_node = Node(data) # calling Node class with passing data 16 | 17 | if self.head is None: # if empty, setting up a head llist 18 | self.head = new_node 19 | else: ## when the List Isn't Empty 20 | last = self.head # We need to find the last node in the list (the one where next is None). So we start at the head (the first node). 21 | while last.next: # loop to keep moving to the next node, while not finding None node 22 | last = last.next 23 | last.next = new_node 24 | 25 | def print(self): 26 | current = self.head 27 | 28 | while current: 29 | print(current.data, end=" -> ") 30 | current = current.next 31 | print("None") 32 | 33 | def lenght(self): 34 | current = self.head 35 | counter = 0 36 | 37 | while current: 38 | counter += 1 39 | current = current.next 40 | return counter 41 | 42 | def searchforvalue(self, value): 43 | current = self.head 44 | 45 | while current: 46 | if current.data == value: 47 | return "Found" 48 | else: 49 | current = current.next 50 | return "Not found" 51 | 52 | def insertatthebeginning(self, value): 53 | insert_node = Node(value) 54 | 55 | if self.head is None: 56 | self.head = insert_node 57 | else: 58 | insert_node.next = self.head 59 | self.head = insert_node 60 | 61 | 62 | 63 | 64 | ll = LinkedList() 65 | ll.append(5) 66 | ll.insertatthebeginning(1) 67 | ll.append(10) 68 | ll.print() 69 | 70 | -------------------------------------------------------------------------------- /linked_list/v2_practise.py: -------------------------------------------------------------------------------- 1 | ##singular linked list 2 | 3 | class Node: 4 | def __init__(self, data): 5 | self.data = data 6 | self.next = None 7 | 8 | class LinkedList: 9 | def __init__(self): 10 | self.head = None 11 | 12 | def append(self, data): 13 | new_node = Node(data) 14 | 15 | if self.head is None: 16 | self.head = new_node 17 | else: 18 | last = self.head 19 | while last.next: 20 | last = last.next 21 | last.next = new_node 22 | 23 | def print_ll(self): 24 | current = self.head 25 | 26 | while current: 27 | print(current.data, end=' --> ') 28 | current = current.next 29 | print("None") 30 | 31 | ll1 = LinkedList() 32 | 33 | ll1.append(1) 34 | ll1.append(2) 35 | ll1.print_ll() -------------------------------------------------------------------------------- /missing_arr/solution.py: -------------------------------------------------------------------------------- 1 | # Input: n = 5, arr[] = [1,2,3,5] 2 | # Output: 4 3 | # Explanation : All the numbers from 1 to 5 are present except 4. 4 | 5 | 6 | n = 2 7 | ar = [1] 8 | 9 | def check_miss(n, ar) -> int: 10 | correct_arr = [i for i in range(1, n+1)] 11 | missing = 0 12 | 13 | for i in correct_arr: 14 | if i not in ar: 15 | missing = i 16 | 17 | if missing != 0: 18 | return missing 19 | else: 20 | return "All good" 21 | 22 | 23 | print(check_miss(n, ar)) -------------------------------------------------------------------------------- /pol_with_x.py: -------------------------------------------------------------------------------- 1 | # Given a string with "?", return a palindrome if possible. EX: ?ab?b returns babab 2 | 3 | strings_to_test = ["?ab??b", "a?b?a", "???", "a?c?b", "a??a", "a?b?c", "??a??", "a??b", "a?b?b?a", "a?b?c?d"] 4 | 5 | def checkpol(string) -> str: 6 | answer_list = [i for i in string] 7 | 8 | if len(answer_list) % 2 != 0: 9 | return "Not a palindrome" 10 | 11 | l, r = 0, len(answer_list) - 1 12 | 13 | while l < r: 14 | if answer_list[l] == "?" and answer_list[r] == "?": 15 | answer_list[l] = "a" 16 | answer_list[r] = "a" 17 | elif answer_list[l] == "?": 18 | answer_list[l] = answer_list[r] 19 | elif answer_list[r] == "?": 20 | answer_list[r] = answer_list[l] 21 | 22 | l += 1 23 | r -= 1 24 | 25 | answer_string = "" 26 | 27 | for i in answer_list: 28 | answer_string += i 29 | 30 | return answer_string 31 | 32 | for i in strings_to_test: 33 | print(checkpol(i)) 34 | -------------------------------------------------------------------------------- /practice_small_code.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "id": "initial_id", 6 | "metadata": { 7 | "collapsed": true, 8 | "ExecuteTime": { 9 | "end_time": "2024-07-31T22:04:46.432484Z", 10 | "start_time": "2024-07-31T22:04:46.423908Z" 11 | } 12 | }, 13 | "source": [ 14 | "for i in range(1,4):\n", 15 | " print(i)" 16 | ], 17 | "outputs": [ 18 | { 19 | "name": "stdout", 20 | "output_type": "stream", 21 | "text": [ 22 | "1\n", 23 | "2\n", 24 | "3\n" 25 | ] 26 | } 27 | ], 28 | "execution_count": 2 29 | }, 30 | { 31 | "metadata": { 32 | "ExecuteTime": { 33 | "end_time": "2024-08-07T03:39:46.132609Z", 34 | "start_time": "2024-08-07T03:39:46.128540Z" 35 | } 36 | }, 37 | "cell_type": "code", 38 | "source": [ 39 | "s = \"bb\"\n", 40 | "list1 = [i for i in s]\n", 41 | "print(len(list1) -1 ) \n", 42 | "print(len(list1))" 43 | ], 44 | "id": "74d716e94aa6f339", 45 | "outputs": [ 46 | { 47 | "name": "stdout", 48 | "output_type": "stream", 49 | "text": [ 50 | "1\n", 51 | "2\n" 52 | ] 53 | } 54 | ], 55 | "execution_count": 6 56 | }, 57 | { 58 | "metadata": { 59 | "ExecuteTime": { 60 | "end_time": "2024-08-07T16:57:33.442540Z", 61 | "start_time": "2024-08-07T16:57:33.438185Z" 62 | } 63 | }, 64 | "cell_type": "code", 65 | "source": [ 66 | "sum = 0\n", 67 | "sum -=100\n", 68 | "print(sum)" 69 | ], 70 | "id": "282cf3c329427e88", 71 | "outputs": [ 72 | { 73 | "name": "stdout", 74 | "output_type": "stream", 75 | "text": [ 76 | "-100\n" 77 | ] 78 | } 79 | ], 80 | "execution_count": 7 81 | }, 82 | { 83 | "metadata": { 84 | "ExecuteTime": { 85 | "end_time": "2024-08-08T01:55:13.160751Z", 86 | "start_time": "2024-08-08T01:55:13.152733Z" 87 | } 88 | }, 89 | "cell_type": "code", 90 | "source": [ 91 | "image = [[1,1,0],[1,0,1],[0,0,0]]\n", 92 | "print(len(image[1]))" 93 | ], 94 | "id": "383ad78972533c49", 95 | "outputs": [ 96 | { 97 | "name": "stdout", 98 | "output_type": "stream", 99 | "text": [ 100 | "3\n" 101 | ] 102 | } 103 | ], 104 | "execution_count": 1 105 | }, 106 | { 107 | "metadata": { 108 | "ExecuteTime": { 109 | "end_time": "2024-08-28T00:41:13.233348Z", 110 | "start_time": "2024-08-28T00:41:13.226317Z" 111 | } 112 | }, 113 | "cell_type": "code", 114 | "source": [ 115 | "list1 = [1,2,4]\n", 116 | "print(len(list1))" 117 | ], 118 | "id": "d5b84c5825e2c378", 119 | "outputs": [ 120 | { 121 | "name": "stdout", 122 | "output_type": "stream", 123 | "text": [ 124 | "3\n" 125 | ] 126 | } 127 | ], 128 | "execution_count": 1 129 | }, 130 | { 131 | "metadata": { 132 | "ExecuteTime": { 133 | "end_time": "2024-09-05T01:04:48.778648Z", 134 | "start_time": "2024-09-05T01:04:48.771965Z" 135 | } 136 | }, 137 | "cell_type": "code", 138 | "source": [ 139 | "string = \"1231\"\n", 140 | "\n", 141 | "for i in string:\n", 142 | " print(i)" 143 | ], 144 | "id": "4484b5192a9f57db", 145 | "outputs": [ 146 | { 147 | "name": "stdout", 148 | "output_type": "stream", 149 | "text": [ 150 | "1\n", 151 | "2\n", 152 | "3\n", 153 | "1\n" 154 | ] 155 | } 156 | ], 157 | "execution_count": 1 158 | }, 159 | { 160 | "metadata": { 161 | "ExecuteTime": { 162 | "end_time": "2024-10-28T13:29:49.491303Z", 163 | "start_time": "2024-10-28T13:29:49.485405Z" 164 | } 165 | }, 166 | "cell_type": "code", 167 | "source": [ 168 | "st = 'string'\n", 169 | "\n", 170 | "st_l = [i for i in st]\n", 171 | "print(st_l)\n", 172 | "answer = [i for i in st_l if i != 'i']\n", 173 | "print(answer)" 174 | ], 175 | "id": "6012818a228328cd", 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "['s', 't', 'r', 'i', 'n', 'g']\n", 182 | "['s', 't', 'r', 'n', 'g']\n" 183 | ] 184 | } 185 | ], 186 | "execution_count": 4 187 | } 188 | ], 189 | "metadata": { 190 | "kernelspec": { 191 | "display_name": "Python 3", 192 | "language": "python", 193 | "name": "python3" 194 | }, 195 | "language_info": { 196 | "codemirror_mode": { 197 | "name": "ipython", 198 | "version": 2 199 | }, 200 | "file_extension": ".py", 201 | "mimetype": "text/x-python", 202 | "name": "python", 203 | "nbconvert_exporter": "python", 204 | "pygments_lexer": "ipython2", 205 | "version": "2.7.6" 206 | } 207 | }, 208 | "nbformat": 4, 209 | "nbformat_minor": 5 210 | } 211 | -------------------------------------------------------------------------------- /solution.py: -------------------------------------------------------------------------------- 1 | # Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] 2 | # such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 3 | # 4 | # Notice that the solution set must not contain duplicate triplets. 5 | # 6 | # 7 | # Example 1: 8 | # 9 | # Input: nums = [-1,0,1,2,-1,-4] 10 | # Output: [[-1,-1,2],[-1,0,1]] 11 | # Explanation: 12 | # nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 13 | # nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 14 | # nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 15 | # The distinct triplets are [-1,0,1] and [-1,-1,2]. 16 | # Notice that the order of the output and the order of the triplets does not matter. 17 | 18 | 19 | nums = [-1,0,1,2,-1,-4] 20 | 21 | def threesum(nums): 22 | # for i in nums: 23 | # for j in nums: 24 | # for k in nums: 25 | # if i + j + k == 0: 26 | # print(f"{i} + {j} + {k} = 0")# 27 | # brute force for fun 28 | # 29 | # dic_nums = {} 30 | # for i, v in enumerate(nums): 31 | # dic_nums[i] = v 32 | # 33 | # 34 | # po1, po2 = 0, 1 35 | # 36 | # 37 | # while po2 < len(nums) -1: 38 | # # if nums[left] + nums[right] == dic -value == 0 39 | # iter = nums[po1] + nums[po2] 40 | # listofsums = [] 41 | # 42 | # for k, v in dic_nums.items(): 43 | # if iter + v == 0: 44 | # listofsums.append([nums[po1], nums[po2], nums[k]]) 45 | # 46 | # po1 += 1 47 | # po2 += 1 48 | # 49 | # return listofsums 50 | 51 | nums.sort() 52 | i = 0 53 | left, right = i+1, len(nums)-1 54 | arr = [] 55 | 56 | # while i < len(nums) - 2: 57 | # if nums[i] + nums[left] + nums[right] == 0: 58 | # res = [nums[i], nums[left], nums[right]] 59 | # arr.append(res) 60 | # i += 1 61 | # left += 1 62 | # right -= 1 63 | 64 | for i in nums: 65 | for j in nums: 66 | if nums[i] + nums[left] + nums[right] == 0: 67 | res = [nums[i], nums[left], nums[right]] 68 | arr.append(res) 69 | i += 1 70 | left += 1 71 | right -= 1 72 | 73 | 74 | 75 | 76 | 77 | 78 | return arr 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | print(threesum(nums)) -------------------------------------------------------------------------------- /test_pose.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mediapipe as mp 3 | import numpy as np 4 | import math 5 | 6 | def calculate_angle(a, b, c): 7 | a = np.array([a.x, a.y]) # First point 8 | b = np.array([b.x, b.y]) # Middle point 9 | c = np.array([c.x, c.y]) # End point 10 | 11 | radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0]) 12 | angle = np.abs(radians*180.0/np.pi) 13 | 14 | if angle > 180.0: 15 | angle = 360 - angle 16 | 17 | return angle 18 | 19 | # Initialize variables 20 | counter = 0 21 | stage = None 22 | 23 | cap = cv2.VideoCapture(0) 24 | mp_pose = mp.solutions.pose 25 | pose = mp_pose.Pose() 26 | mp_drawing = mp.solutions.drawing_utils 27 | 28 | while cap.isOpened(): 29 | ret, frame = cap.read() 30 | if not ret: 31 | break 32 | 33 | # Recolor image to RGB 34 | image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 35 | image.flags.writeable = False 36 | 37 | # Make detection 38 | results = pose.process(image) 39 | 40 | # Recolor back to BGR 41 | image.flags.writeable = True 42 | image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) 43 | 44 | # Extract landmarks 45 | try: 46 | landmarks = results.pose_landmarks.landmark 47 | 48 | # Get coordinates 49 | left_hip = landmarks[mp_pose.PoseLandmark.LEFT_HIP] 50 | left_knee = landmarks[mp_pose.PoseLandmark.LEFT_KNEE] 51 | left_ankle = landmarks[mp_pose.PoseLandmark.LEFT_ANKLE] 52 | 53 | # Calculate angle 54 | angle = calculate_angle(left_hip, left_knee, left_ankle) 55 | 56 | # Visualize angle 57 | cv2.putText(image, str(int(angle)), 58 | (int(left_knee.x * image.shape[1]), int(left_knee.y * image.shape[0])), 59 | cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) 60 | 61 | # Squat logic 62 | if angle > 160: 63 | stage = 'up' 64 | if angle < 90 and stage == 'up': 65 | stage = 'down' 66 | counter += 1 67 | print(f"Squat count: {counter}") 68 | 69 | except Exception as e: 70 | pass 71 | 72 | # Render squat count 73 | cv2.rectangle(image, (0, 0), (225, 73), (245, 117, 16), -1) 74 | cv2.putText(image, 'REPS', (15, 12), 75 | cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) 76 | cv2.putText(image, str(counter), 77 | (10, 60), 78 | cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) 79 | 80 | # Display image 81 | cv2.imshow('Knee Exercise', image) 82 | 83 | if cv2.waitKey(10) & 0xFF == ord('q'): 84 | break 85 | 86 | cap.release() 87 | cv2.destroyAllWindows() 88 | --------------------------------------------------------------------------------