├── 1st_occurence.py ├── 3SUM-closet.py ├── 3SUM.py ├── 4SUM.py ├── Container_water.py ├── Int_to_col.py ├── Integer-Roman.py ├── IsMatch.py ├── Largest_product_in_series.py ├── Longest_common_prefix.py ├── Nth_prime.py ├── Nth_prime2.py ├── Palindrome.py ├── Permutation.py ├── Quiz.py ├── Rational.py ├── Remove_Duplicate_from_sortedarray.py ├── Remove_Nth_node.py ├── Repeated_substring.py ├── Reverse-Integer.py ├── Reverse_element.py ├── Roman-integer.py ├── Rotate_arr.py ├── Search_element.py ├── Search_range.py ├── Zigzag.py ├── armstrong.py ├── com_sum.py ├── com_sum2.py ├── even_fibonnaci.py ├── firstmissingpositive.py ├── fulljustfiy.py ├── generate-paranthesis.py ├── graph.py ├── largest_Palindrome_product.py ├── largest_prime.py ├── letter-combinations-of-a-phone-number.py ├── list.py ├── longest_valid_braces.py ├── multiply.py ├── palindrome_partioning.py ├── paranthesis.py ├── pascal.py ├── perm.py ├── qr.py ├── questions.txt ├── requirements.txt ├── reverse_node_kgroup.py ├── rotate_matrix.py ├── runner.py ├── search_insert.py ├── search_matrix.py ├── smallest_multiple.py ├── stack_using-queues.py ├── string to integer(atoi).py ├── sudoku_solver.py ├── sum_of_15.py ├── sum_of_square.py ├── swap_nodes.py ├── trap.py └── valid_sudoku.py /1st_occurence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def strStr(self, haystack, needle): 3 | """ 4 | :type haystack: str 5 | :type needle: str 6 | :rtype: int 7 | """ 8 | if not needle: 9 | return 0 # If needle is an empty string, return 0. 10 | 11 | for i in range(len(haystack) - len(needle) + 1): 12 | if haystack[i:i + len(needle)] == needle: 13 | return i 14 | 15 | return -1 # If needle is not found in haystack, return -1. 16 | 17 | # test case 1 18 | haystack = "sadbutsad" 19 | needle = "sad" 20 | 21 | print("Haystack:-",haystack) 22 | print("Needle:-",needle) 23 | sol = Solution() 24 | out = sol.strStr(haystack,needle) 25 | print("OCCURENCE:-",out) 26 | 27 | # Given two strings needle and haystack, return the index of the first occurrence 28 | # of needle in haystack, or -1 if needle is not part of haystack. -------------------------------------------------------------------------------- /3SUM-closet.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def threeSumClosest(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | nums.sort() # Sort the array in ascending order 9 | closest_sum = float('inf') 10 | 11 | for i in range(len(nums) - 2): 12 | left, right = i + 1, len(nums) - 1 13 | 14 | while left < right: 15 | total = nums[i] + nums[left] + nums[right] 16 | if total == target: 17 | return total 18 | 19 | if abs(total - target) < abs(closest_sum - target): 20 | closest_sum = total 21 | 22 | if total < target: 23 | left += 1 24 | else: 25 | right -= 1 26 | 27 | return closest_sum 28 | 29 | # Test cases 30 | solution = Solution() 31 | l=[-1,2,1,-4] 32 | t=[0,0,0] 33 | 34 | print(l) 35 | print(t) 36 | print(solution.threeSumClosest([-1,2,1,-4], 1)) # Output: 2 37 | print(solution.threeSumClosest([0,0,0], 1)) # Output: 0 38 | #Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. 39 | #Return the sum of the three integers. -------------------------------------------------------------------------------- /3SUM.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def threeSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | nums.sort() # Sort the array in ascending order 8 | result = [] 9 | 10 | for i in range(len(nums) - 2): 11 | if i > 0 and nums[i] == nums[i - 1]: 12 | continue # Skip duplicate elements 13 | 14 | left, right = i + 1, len(nums) - 1 15 | target = -nums[i] 16 | 17 | while left < right: 18 | if nums[left] + nums[right] == target: 19 | result.append([nums[i], nums[left], nums[right]]) 20 | while left < right and nums[left] == nums[left + 1]: 21 | left += 1 # Skip duplicate elements 22 | while left < right and nums[right] == nums[right - 1]: 23 | right -= 1 # Skip duplicate elements 24 | left += 1 25 | right -= 1 26 | elif nums[left] + nums[right] < target: 27 | left += 1 28 | else: 29 | right -= 1 30 | 31 | return result 32 | 33 | # Test case 34 | l=[-1,0,1,2,-1,-4] 35 | solution = Solution() 36 | 37 | print(l) 38 | print(solution.threeSum(l)) # Output: [[-1,-1,2],[-1,0,1]] 39 | -------------------------------------------------------------------------------- /4SUM.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fourSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[List[int]] 7 | """ 8 | nums.sort() # Sort the array in ascending order 9 | result = [] 10 | 11 | for i in range(len(nums) - 3): 12 | if i > 0 and nums[i] == nums[i - 1]: 13 | continue # Skip duplicate elements 14 | 15 | for j in range(i + 1, len(nums) - 2): 16 | if j > i + 1 and nums[j] == nums[j - 1]: 17 | continue # Skip duplicate elements 18 | 19 | left, right = j + 1, len(nums) - 1 20 | 21 | while left < right: 22 | total = nums[i] + nums[j] + nums[left] + nums[right] 23 | 24 | if total == target: 25 | result.append([nums[i], nums[j], nums[left], nums[right]]) 26 | while left < right and nums[left] == nums[left + 1]: 27 | left += 1 # Skip duplicate elements 28 | while left < right and nums[right] == nums[right - 1]: 29 | right -= 1 # Skip duplicate elements 30 | left += 1 31 | right -= 1 32 | elif total < target: 33 | left += 1 34 | else: 35 | right -= 1 36 | 37 | return result 38 | 39 | # Test case 40 | solution = Solution() 41 | print(solution.fourSum([1,0,-1,0,-2,2], 0)) # Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] 42 | print(solution.fourSum([2,2,2,2,2], 8)) # Output: [[2,2,2,2]] 43 | -------------------------------------------------------------------------------- /Container_water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | max_area = 0 8 | left = 0 9 | right = len(height) - 1 10 | 11 | while left < right: 12 | h = min(height[left], height[right]) 13 | w = right - left 14 | area = h * w 15 | max_area = max(max_area, area) 16 | 17 | if height[left] < height[right]: 18 | left += 1 19 | else: 20 | right -= 1 21 | 22 | return max_area 23 | 24 | import matplotlib.pyplot as plt 25 | import numpy as np 26 | 27 | n=np.arange(9) 28 | height = [1,8,6,2,5,4,8,3,7] 29 | 30 | plt.bar(n,height) 31 | plt.show() 32 | sol = Solution() 33 | out = sol.maxArea(height) 34 | print(out) -------------------------------------------------------------------------------- /Int_to_col.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToTitle(self, columnNumber): 3 | """ 4 | :type columnNumber: int 5 | :rtype: str 6 | """ 7 | result = "" 8 | while columnNumber > 0: 9 | # Convert to 0-based index 10 | columnNumber -= 1 11 | remainder = columnNumber % 26 12 | result = chr(65 + remainder) + result 13 | columnNumber //= 26 14 | return result 15 | 16 | # Example usage 17 | sol = Solution() 18 | n=int(input("Enter a number:-")) 19 | out = sol.convertToTitle(n) 20 | print(out) 21 | -------------------------------------------------------------------------------- /Integer-Roman.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intToRoman(self, num): 3 | """ 4 | :type num: int 5 | :rtype: str 6 | """ 7 | roman_numerals = { 8 | 1: 'I', 9 | 4: 'IV', 10 | 5: 'V', 11 | 9: 'IX', 12 | 10: 'X', 13 | 40: 'XL', 14 | 50: 'L', 15 | 90: 'XC', 16 | 100: 'C', 17 | 400: 'CD', 18 | 500: 'D', 19 | 900: 'CM', 20 | 1000: 'M' 21 | } 22 | 23 | result = '' 24 | # Sort the keys in reverse order (largest to smallest) 25 | sorted_keys = sorted(roman_numerals.keys(), reverse=True) 26 | 27 | for key in sorted_keys: 28 | while num >= key: 29 | result += roman_numerals[key] 30 | num -= key 31 | 32 | return result 33 | 34 | 35 | sol = Solution() 36 | num = int(input("Enter a number:-")) 37 | out = sol.intToRoman(num) 38 | print(out) -------------------------------------------------------------------------------- /IsMatch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isMatch(self, s, p): 3 | """ 4 | :type s: str 5 | :type p: str 6 | :rtype: bool 7 | """ 8 | m, n = len(s), len(p) 9 | dp = [[False] * (n + 1) for _ in range(m + 1)] 10 | dp[0][0] = True 11 | 12 | for i in range(m + 1): 13 | for j in range(1, n + 1): 14 | if p[j - 1] == '*': 15 | dp[i][j] = dp[i][j - 2] or (i > 0 and (s[i - 1] == p[j - 2] or p[j - 2] == '.') and dp[i - 1][j]) 16 | else: 17 | dp[i][j] = i > 0 and (s[i - 1] == p[j - 1] or p[j - 1] == '.') and dp[i - 1][j - 1] 18 | 19 | return dp[m][n] 20 | 21 | # Test cases 22 | solution = Solution() 23 | print(solution.isMatch("aa", "a")) # Output: False 24 | print(solution.isMatch("aa", "a*")) # Output: True 25 | print(solution.isMatch("ab", ".*")) # Output: True 26 | -------------------------------------------------------------------------------- /Largest_product_in_series.py: -------------------------------------------------------------------------------- 1 | def find_greatest_product(num, k): 2 | max_product = 0 3 | for i in range(len(num) - k + 1): 4 | product = 1 5 | for j in range(i, i + k): 6 | product *= int(num[j]) 7 | max_product = max(max_product, product) 8 | return max_product 9 | 10 | if __name__ == '__main__': 11 | t = int(input("Enter test cases:-").strip()) 12 | for _ in range(t): 13 | n, k = map(int, input("Enter N & K respectively(10,5):-").strip().split()) 14 | num = input("Enter a long number(e.g 3675356291):-").strip() 15 | result = find_greatest_product(num, k) 16 | print(result) 17 | -------------------------------------------------------------------------------- /Longest_common_prefix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestCommonPrefix(self, strs): 3 | """ 4 | :type strs: List[str] 5 | :rtype: str 6 | """ 7 | if not strs: 8 | return "None" 9 | 10 | # Find the minimum length string in the array 11 | min_len = min(len(s) for s in strs) 12 | 13 | # Iterate through characters at the same index in all strings 14 | for i in range(min_len): 15 | char = strs[0][i] 16 | if any(s[i] != char for s in strs[1:]): 17 | return strs[0][:i] 18 | 19 | return strs[0][:min_len] 20 | 21 | # Test cases 22 | solution = Solution() 23 | print(solution.longestCommonPrefix(["flower","flow","flight"])) # Output: "fl" 24 | print(solution.longestCommonPrefix(["dog","racecar","car"])) # Output: "" 25 | -------------------------------------------------------------------------------- /Nth_prime.py: -------------------------------------------------------------------------------- 1 | def is_prime(num): 2 | if num <= 1: 3 | return False 4 | if num <= 3: 5 | return True 6 | if num % 2 == 0 or num % 3 == 0: 7 | return False 8 | i = 5 9 | while i * i <= num: 10 | if num % i == 0 or num % (i + 2) == 0: 11 | return False 12 | i += 6 13 | return True 14 | 15 | def nth_prime(n): 16 | count = 0 17 | num = 1 18 | while count < n: 19 | num += 1 20 | if is_prime(num): 21 | count += 1 22 | return num 23 | 24 | if __name__ == '__main__': 25 | t = int(input("Enter test cases:-").strip()) 26 | for _ in range(t): 27 | n = int(input("Enter a prime number:-").strip()) 28 | result = nth_prime(n) 29 | print(result) 30 | -------------------------------------------------------------------------------- /Nth_prime2.py: -------------------------------------------------------------------------------- 1 | def prime_numbers(limit): 2 | primes = [] 3 | is_prime = [True] * (limit + 1) 4 | is_prime[0] = is_prime[1] = False 5 | for num in range(2, limit + 1): 6 | if is_prime[num]: 7 | primes.append(num) 8 | for multiple in range(num * num, limit + 1, num): 9 | is_prime[multiple] = False 10 | return primes 11 | 12 | def nth_prime(n, primes): 13 | return primes[n - 1] 14 | 15 | if __name__ == '__main__': 16 | max_limit = 10 ** 6 # Adjust this limit based on your requirements 17 | primes = prime_numbers(max_limit) 18 | 19 | t = int(input("Enter test cases:-").strip()) 20 | for _ in range(t): 21 | n = int(input("Enter a number:-").strip()) 22 | result = nth_prime(n, primes) 23 | print(result) 24 | -------------------------------------------------------------------------------- /Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, x): 3 | # Convert the integer to a string 4 | x_str = str(x) 5 | 6 | # Check if the string is equal to its reverse 7 | return x_str == x_str[::-1] 8 | 9 | 10 | 11 | sol = Solution() 12 | num=121 13 | out = sol.isPalindrome(num) 14 | 15 | print(out) -------------------------------------------------------------------------------- /Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nextPermutation(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: None Do not return anything, modify nums in-place instead. 6 | """ 7 | # Step 1: Find the first element from the right that is smaller than its right neighbor 8 | i = len(nums) - 2 9 | while i >= 0 and nums[i] >= nums[i + 1]: 10 | i -= 1 11 | 12 | if i >= 0: 13 | # Step 2: Find the smallest element to the right of nums[i] that is greater than nums[i] 14 | j = len(nums) - 1 15 | while nums[j] <= nums[i]: 16 | j -= 1 17 | # Step 3: Swap nums[i] and nums[j] 18 | nums[i], nums[j] = nums[j], nums[i] 19 | 20 | # Step 4: Reverse the subarray to the right of nums[i] 21 | left, right = i + 1, len(nums) - 1 22 | while left < right: 23 | nums[left], nums[right] = nums[right], nums[left] 24 | left += 1 25 | right -= 1 26 | 27 | # Example usage 28 | solution = Solution() 29 | nums1 = [1, 2, 3] 30 | solution.nextPermutation(nums1) 31 | print(nums1) # Output: [1, 3, 2] 32 | 33 | nums2 = [3, 2, 1] 34 | solution.nextPermutation(nums2) 35 | print(nums2) # Output: [1, 2, 3] 36 | 37 | nums3 = [1, 1, 5] 38 | solution.nextPermutation(nums3) 39 | print(nums3) # Output: [1, 5, 1] 40 | -------------------------------------------------------------------------------- /Quiz.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | class QuizApplication: 4 | def __init__(self, root): 5 | self.root = root 6 | self.questions = self.load_questions() 7 | self.total_questions = len(self.questions) 8 | self.current_question = 0 9 | self.correct_answers = 0 10 | 11 | self.question_label = tk.Label(root, text="", wraplength=400, font=("Arial", 14)) 12 | self.question_label.pack(pady=20) 13 | 14 | self.options_frame = tk.Frame(root) 15 | self.options_frame.pack(pady=20) 16 | 17 | self.answer_label = tk.Label(root, text="", font=("Arial", 12)) 18 | self.answer_label.pack(pady=10) 19 | 20 | self.next_button = tk.Button(root, text="Next", command=self.next_question) 21 | self.next_button.pack(pady=10) 22 | 23 | self.display_question() 24 | 25 | def load_questions(self): 26 | questions = [] 27 | with open("questions.txt", "r") as file: 28 | lines = file.readlines() 29 | question = {} 30 | for line in lines: 31 | line = line.strip() 32 | if line.startswith("Question"): 33 | if question: 34 | questions.append(question) 35 | question = {} 36 | question["text"] = line 37 | elif line.startswith("Correct Answer"): 38 | question["answer"] = line.split(":")[1].strip().lower() 39 | elif line.startswith(("a)", "b)", "c)", "d)")): 40 | option, text = line.split(")", 1) 41 | question[option.strip().lower()] = text.strip() 42 | if question: 43 | questions.append(question) 44 | return questions 45 | 46 | 47 | def display_question(self): 48 | question = self.questions[self.current_question] 49 | self.question_label.config(text=question["text"]) 50 | 51 | for widget in self.options_frame.winfo_children(): 52 | widget.destroy() 53 | 54 | for option in question: 55 | if option != "text" and option != "answer": 56 | button = tk.Button(self.options_frame, text=f"{option.upper()}. {question[option]}", 57 | command=lambda option=option: self.check_answer(option)) 58 | button.pack(pady=5) 59 | 60 | def check_answer(self, selected_option): 61 | question = self.questions[self.current_question] 62 | correct_answer = question["answer"] 63 | 64 | if selected_option == correct_answer: 65 | self.correct_answers += 1 66 | self.answer_label.config(text="Correct!", fg="green") 67 | else: 68 | self.answer_label.config(text="Incorrect!", fg="red") 69 | 70 | self.next_button.config(state=tk.NORMAL) 71 | 72 | for widget in self.options_frame.winfo_children(): 73 | widget.config(state=tk.DISABLED) 74 | 75 | def next_question(self): 76 | self.current_question += 1 77 | 78 | if self.current_question < self.total_questions: 79 | self.display_question() 80 | self.next_button.config(state=tk.DISABLED) 81 | self.answer_label.config(text="") 82 | else: 83 | self.show_report() 84 | 85 | def show_report(self): 86 | report = f"Number of questions asked: {self.total_questions}\n" 87 | report += f"Number of questions answered correctly: {self.correct_answers}" 88 | 89 | self.question_label.config(text="Quiz Completed!") 90 | self.answer_label.config(text=report) 91 | self.next_button.config(text="Exit", command=self.root.quit) 92 | 93 | root = tk.Tk() 94 | root.title("Quiz Application") 95 | app = QuizApplication(root) 96 | root.mainloop() 97 | -------------------------------------------------------------------------------- /Rational.py: -------------------------------------------------------------------------------- 1 | class Rational: 2 | def __init__(self, numerator, denominator): 3 | self.numerator = numerator 4 | self.denominator = denominator 5 | 6 | def __add__(self, other): 7 | new_numerator = self.numerator * other.denominator + other.numerator * self.denominator 8 | new_denominator = self.denominator * other.denominator 9 | return Rational(new_numerator, new_denominator) 10 | 11 | def __sub__(self, other): 12 | new_numerator = self.numerator * other.denominator - other.numerator * self.denominator 13 | new_denominator = self.denominator * other.denominator 14 | return Rational(new_numerator, new_denominator) 15 | 16 | def __mul__(self, other): 17 | new_numerator = self.numerator * other.numerator 18 | new_denominator = self.denominator * other.denominator 19 | return Rational(new_numerator, new_denominator) 20 | 21 | def __truediv__(self, other): 22 | new_numerator = self.numerator * other.denominator 23 | new_denominator = self.denominator * other.numerator 24 | return Rational(new_numerator, new_denominator) 25 | 26 | def display(self): 27 | print(f"{self.numerator} / {self.denominator}") 28 | 29 | 30 | # Sample usage 31 | numerator1 = int(input("Enter numerator for the first rational number: ")) 32 | denominator1 = int(input("Enter denominator for the first rational number: ")) 33 | numerator2 = int(input("Enter numerator for the second rational number: ")) 34 | denominator2 = int(input("Enter denominator for the second rational number: ")) 35 | 36 | r1 = Rational(numerator1, denominator1) 37 | r2 = Rational(numerator2, denominator2) 38 | 39 | # Addition 40 | result = r1 + r2 41 | result.display() 42 | 43 | # Subtraction 44 | result = r1 - r2 45 | result.display() 46 | 47 | # Multiplication 48 | result = r1 * r2 49 | result.display() 50 | 51 | # Division 52 | result = r1 / r2 53 | result.display() 54 | -------------------------------------------------------------------------------- /Remove_Duplicate_from_sortedarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if not nums: 8 | return 0 # If the array is empty, there are no duplicates 9 | 10 | k = 1 # Initialize the pointer for the new length of the modified array 11 | 12 | for i in range(1, len(nums)): 13 | if nums[i] != nums[i - 1]: 14 | nums[k] = nums[i] # Replace the duplicate with the new element 15 | k += 1 16 | 17 | return k # k represents the new length of the modified array 18 | 19 | # Example usage 20 | solution = Solution() 21 | nums1 = [1, 1, 2] 22 | length1 = solution.removeDuplicates(nums1) 23 | print(length1) # Output: 2, nums1 = [1, 2, ...] 24 | 25 | nums2 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] 26 | length2 = solution.removeDuplicates(nums2) 27 | print(length2) # Output: 5, nums2 = [0, 1, 2, 3, 4, ...] 28 | -------------------------------------------------------------------------------- /Remove_Nth_node.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | class Solution: 7 | def removeNthFromEnd(self, head, n): 8 | dummy = ListNode(0) 9 | dummy.next = head 10 | fast = slow = dummy 11 | 12 | # Move fast pointer n steps ahead 13 | for _ in range(n + 1): 14 | fast = fast.next 15 | 16 | # Move fast and slow pointers until fast reaches the end 17 | while fast: 18 | fast = fast.next 19 | slow = slow.next 20 | 21 | # Remove the nth node from the end 22 | slow.next = slow.next.next 23 | 24 | return dummy.next 25 | 26 | # Helper function to create a linked list from a list 27 | def create_linked_list(values): 28 | dummy = ListNode(0) 29 | current = dummy 30 | for val in values: 31 | current.next = ListNode(val) 32 | current = current.next 33 | return dummy.next 34 | 35 | def print_linked_list(head): 36 | current = head 37 | while current: 38 | print(current.val, end=" -> ") 39 | current = current.next 40 | print("None") 41 | 42 | # Helper function to convert linked list to list 43 | def linked_list_to_list(head): 44 | result = [] 45 | while head: 46 | result.append(head.val) 47 | head = head.next 48 | return result 49 | 50 | # Test cases 51 | solution = Solution() 52 | head1 = create_linked_list([1,2,3,4,5]) 53 | result1 = solution.removeNthFromEnd(head1, 2) 54 | print(linked_list_to_list(result1)) # Output: [1, 2, 3, 5] 55 | print_linked_list(head1) 56 | 57 | 58 | head2 = create_linked_list([1]) 59 | result2 = solution.removeNthFromEnd(head2, 1) 60 | print(linked_list_to_list(result2)) # Output: [] 61 | print_linked_list(head2) 62 | 63 | head3 = create_linked_list([1,2]) 64 | result3 = solution.removeNthFromEnd(head3, 1) 65 | print(linked_list_to_list(result3)) # Output: [1] 66 | print_linked_list(head3) 67 | 68 | head = create_linked_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 69 | print_linked_list(head) -------------------------------------------------------------------------------- /Repeated_substring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def repeatedSubstringPattern(self, s): 3 | n = len(s) 4 | 5 | for i in range(1, n): 6 | if n % i == 0 and s[:i] * (n // i) == s: 7 | return True 8 | 9 | return False 10 | 11 | # Test cases 12 | solution = Solution() 13 | print(solution.repeatedSubstringPattern("abab")) # Output: True 14 | print(solution.repeatedSubstringPattern("aba")) # Output: False 15 | print(solution.repeatedSubstringPattern("abcabcabcabc")) # Output: True 16 | -------------------------------------------------------------------------------- /Reverse-Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x): 3 | if x < 0: 4 | sign = -1 5 | x = abs(x) 6 | else: 7 | sign = 1 8 | 9 | reversed_x = 0 10 | while x != 0: 11 | print(x) 12 | digit = x % 10 13 | reversed_x = reversed_x * 10 + digit 14 | x //= 10 15 | print(x) 16 | 17 | # Checking for overflow 18 | if reversed_x > 2**31 - 1 or reversed_x < -2**31: 19 | return 0 20 | 21 | return sign * reversed_x 22 | 23 | sol = Solution() 24 | 25 | out = sol.reverse(123) 26 | print(out) # Output should be 321 27 | -------------------------------------------------------------------------------- /Reverse_element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | k = 0 # Initialize the pointer for the new length of the modified array 9 | 10 | for i in range(len(nums)): 11 | if nums[i] != val: 12 | nums[k] = nums[i] # Replace the element to be removed with the new element 13 | k += 1 14 | 15 | return k # k represents the new length of the modified array 16 | 17 | # Example usage 18 | solution = Solution() 19 | nums1 = [3, 2, 2, 3] 20 | val1 = 3 21 | length1 = solution.removeElement(nums1, val1) 22 | print(length1) # Output: 2, nums1 = [2, 2, ...] 23 | 24 | nums2 = [0, 1, 2, 2, 3, 0, 4, 2] 25 | val2 = 2 26 | length2 = solution.removeElement(nums2, val2) 27 | print(length2) # Output: 5, nums2 = [0, 1, 4, 0, 3, ...] 28 | -------------------------------------------------------------------------------- /Roman-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | roman_to_int = { 8 | 'I': 1, 'V': 5, 'X': 10, 'L': 50, 9 | 'C': 100, 'D': 500, 'M': 1000 10 | } 11 | 12 | prev_value = 0 13 | total = 0 14 | 15 | for symbol in s: 16 | value = roman_to_int[symbol] 17 | if value > prev_value: 18 | total += value - 2 * prev_value 19 | else: 20 | total += value 21 | prev_value = value 22 | 23 | return total 24 | 25 | # Test cases 26 | solution = Solution() 27 | print(solution.romanToInt("III")) # Output: 3 28 | print(solution.romanToInt("LVIII")) # Output: 58 29 | print(solution.romanToInt("MCMXCIV")) # Output: 1994 30 | -------------------------------------------------------------------------------- /Rotate_arr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: list[int], k: int) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | n = len(nums) 7 | k = k % n # Ensure k is within the range of array size 8 | 9 | # Reverse the entire array 10 | self.reverse(nums, 0, n - 1) 11 | 12 | # Reverse the first k elements 13 | self.reverse(nums, 0, k - 1) 14 | 15 | # Reverse the remaining elements 16 | self.reverse(nums, k, n - 1) 17 | 18 | def reverse(self, nums: list[int], start: int, end: int) -> None: 19 | """ 20 | Helper function to reverse elements in nums from 'start' to 'end'. 21 | """ 22 | while start < end: 23 | nums[start], nums[end] = nums[end], nums[start] 24 | start += 1 25 | end -= 1 26 | 27 | sol = Solution() 28 | nums1 = [1, 2, 3, 4, 5, 6, 7] 29 | k1 = 3 30 | sol.rotate(nums1, k1) 31 | print(nums1) # Output: [5, 6, 7, 1, 2, 3, 4] 32 | 33 | nums2 = [-1, -100, 3, 99] 34 | k2 = 2 35 | sol.rotate(nums2, k2) 36 | print(nums2) # Output: [3, 99, -1, -100] 37 | -------------------------------------------------------------------------------- /Search_element.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def search(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | left, right = 0, len(nums) - 1 9 | 10 | while left <= right: 11 | mid = left + (right - left) // 2 12 | 13 | if nums[mid] == target: 14 | return mid 15 | 16 | if nums[left] <= nums[mid]: 17 | if nums[left] <= target < nums[mid]: 18 | right = mid - 1 19 | else: 20 | left = mid + 1 21 | else: 22 | if nums[mid] < target <= nums[right]: 23 | left = mid + 1 24 | else: 25 | right = mid - 1 26 | 27 | return -1 28 | 29 | solution = Solution() 30 | nums1 = [4, 5, 6, 7, 0, 1, 2] 31 | target1 = 0 32 | print(solution.search(nums1, target1)) # Output: 4 33 | 34 | nums2 = [4, 5, 6, 7, 0, 1, 2] 35 | target2 = 3 36 | print(solution.search(nums2, target2)) # Output: -1 37 | 38 | nums3 = [1] 39 | target3 = 0 40 | print(solution.search(nums3, target3)) # Output: -1 41 | -------------------------------------------------------------------------------- /Search_range.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchRange(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | result = [-1, -1] # Initialize the result with [-1, -1] 9 | 10 | # Binary search for the left boundary 11 | left, right = 0, len(nums) - 1 12 | while left <= right: 13 | mid = left + (right - left) // 2 14 | if nums[mid] == target: 15 | result[0] = mid 16 | right = mid - 1 17 | elif nums[mid] < target: 18 | left = mid + 1 19 | else: 20 | right = mid - 1 21 | 22 | # Binary search for the right boundary 23 | left, right = 0, len(nums) - 1 24 | while left <= right: 25 | mid = left + (right - left) // 2 26 | if nums[mid] == target: 27 | result[1] = mid 28 | left = mid + 1 29 | elif nums[mid] < target: 30 | left = mid + 1 31 | else: 32 | right = mid - 1 33 | 34 | return result 35 | 36 | sol = Solution() 37 | l = [10, 20, 20, 30, 40] 38 | target = 20 39 | out = sol.searchRange(l, target) 40 | print(l) 41 | print(target) 42 | print(out) 43 | -------------------------------------------------------------------------------- /Zigzag.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convert(self, s, numRows): 3 | if numRows == 1 or numRows >= len(s): 4 | return s 5 | 6 | rows = [''] * numRows 7 | current_row = 0 8 | direction = 1 9 | 10 | for char in s: 11 | rows[current_row] += char 12 | 13 | if current_row == 0: 14 | direction = 1 15 | elif current_row == numRows - 1: 16 | direction = -1 17 | 18 | current_row += direction 19 | 20 | result = ''.join(rows) 21 | 22 | return result 23 | 24 | # Example 1 25 | s1 = "PAYPALISHIRING" 26 | numRows1 = 3 27 | solution = Solution() 28 | output1 = solution.convert(s1, numRows1) 29 | print(output1) # Output should be "PAHNAPLSIIGYIR" 30 | 31 | # Example 2 32 | s2 = "PAYPALISHIRING" 33 | numRows2 = 4 34 | output2 = solution.convert(s2, numRows2) 35 | print(output2) # Output should be "PINALSIGYAHRPI" 36 | -------------------------------------------------------------------------------- /armstrong.py: -------------------------------------------------------------------------------- 1 | def is_armstrong_number(n): 2 | # Convert the number to a string to extract digits 3 | num_str = str(n) 4 | num_digits = len(num_str) 5 | 6 | # Calculate the sum of the cube of each digit 7 | armstrong_sum = sum(int(digit) ** num_digits for digit in num_str) 8 | 9 | # Check if the sum is equal to the original number 10 | return armstrong_sum == n 11 | 12 | # Read the number of test cases 13 | T = int(input()) 14 | 15 | # Process each test case 16 | for _ in range(T): 17 | num = int(input()) 18 | if is_armstrong_number(num): 19 | print("It is an ARMSTRONG number") 20 | else: 21 | print("It is NOT an ARMSTRONG number") 22 | -------------------------------------------------------------------------------- /com_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates, target): 3 | def backtrack(start, target, current_combination): 4 | if target == 0: 5 | result.append(current_combination[:]) 6 | return 7 | if target < 0: 8 | return 9 | for i in range(start, len(candidates)): 10 | current_combination.append(candidates[i]) 11 | backtrack(i, target - candidates[i], current_combination) 12 | current_combination.pop() 13 | 14 | result = [] 15 | backtrack(0, target, []) 16 | return result 17 | 18 | # Example test cases 19 | candidates1 = [2, 3, 6, 7] 20 | target1 = 7 21 | 22 | candidates2 = [2, 3, 5] 23 | target2 = 8 24 | 25 | candidates3 = [2] 26 | target3 = 1 27 | 28 | solution = Solution() 29 | print(solution.combinationSum(candidates1, target1)) # Output: [[2, 2, 3], [7]] 30 | print(solution.combinationSum(candidates2, target2)) # Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]] 31 | print(solution.combinationSum(candidates3, target3)) # Output: [] 32 | -------------------------------------------------------------------------------- /com_sum2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum2(self, candidates, target): 3 | def backtrack(start, target, current_combination): 4 | if target == 0: 5 | result.append(current_combination[:]) 6 | return 7 | if target < 0: 8 | return 9 | 10 | for i in range(start, len(candidates)): 11 | if i > start and candidates[i] == candidates[i - 1]: 12 | continue # Skip duplicates to avoid duplicate combinations 13 | current_combination.append(candidates[i]) 14 | backtrack(i + 1, target - candidates[i], current_combination) # Use the next candidate 15 | current_combination.pop() 16 | 17 | result = [] 18 | candidates.sort() # Sort candidates to handle duplicates 19 | backtrack(0, target, []) 20 | return result 21 | 22 | # Example test cases 23 | candidates1 = [10, 1, 2, 7, 6, 1, 5] 24 | target1 = 8 25 | 26 | candidates2 = [2, 5, 2, 1, 2] 27 | target2 = 5 28 | 29 | solution = Solution() 30 | print(solution.combinationSum2(candidates1, target1)) 31 | # Output: [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]] 32 | 33 | print(solution.combinationSum2(candidates2, target2)) 34 | # Output: [[1, 2, 2], [5]] 35 | 36 | #Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. 37 | 38 | #Each number in candidates may only be used once in the combination. 39 | 40 | #Note: The solution set must not contain duplicate combinations. 41 | -------------------------------------------------------------------------------- /even_fibonnaci.py: -------------------------------------------------------------------------------- 1 | def even_fibonacci_sum(limit): 2 | a, b = 1, 2 3 | total_sum = 0 4 | while b <= limit: 5 | if b % 2 == 0: 6 | total_sum += b 7 | a, b = b, a + b 8 | return total_sum 9 | 10 | if __name__ == '__main__': 11 | t = int(input("enter test cases:-").strip()) 12 | for _ in range(t): 13 | n = int(input("enter a number:-").strip()) 14 | result = even_fibonacci_sum(n) 15 | print(result) 16 | -------------------------------------------------------------------------------- /firstmissingpositive.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstMissingPositive(self,nums): 3 | n = len(nums) 4 | 5 | # First, move all positive integers to their correct positions. 6 | for i in range(n): 7 | while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: 8 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] 9 | 10 | # Iterate through the modified array to find the missing positive integer. 11 | for i in range(n): 12 | if nums[i] != i + 1: 13 | return i + 1 14 | 15 | return n + 1 16 | 17 | 18 | 19 | l=[1,2,0] 20 | sol = Solution() 21 | out = sol.firstMissingPositive(l) 22 | print(out) 23 | -------------------------------------------------------------------------------- /fulljustfiy.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fullJustify(self, words, maxWidth): 3 | """ 4 | :type words: List[str] 5 | :type maxWidth: int 6 | :rtype: List[str] 7 | """ 8 | result = [] 9 | line = [] 10 | line_length = 0 11 | 12 | for word in words: 13 | # Check if the current word can fit in the current line 14 | if line_length + len(line) + len(word) <= maxWidth: 15 | line.append(word) 16 | line_length += len(word) 17 | else: 18 | # Distribute spaces evenly in the line 19 | spaces = maxWidth - line_length 20 | if len(line) == 1: 21 | result.append(line[0] + ' ' * spaces) 22 | else: 23 | extra_spaces = spaces % (len(line) - 1) 24 | space_per_word = spaces // (len(line) - 1) 25 | line_str = "" 26 | for i in range(len(line) - 1): 27 | line_str += line[i] 28 | line_str += ' ' * (space_per_word + (1 if i < extra_spaces else 0)) 29 | line_str += line[-1] 30 | result.append(line_str) 31 | 32 | # Reset the line 33 | line = [word] 34 | line_length = len(word) 35 | 36 | # Left-justify the last line 37 | last_line = ' '.join(line) 38 | last_line += ' ' * (maxWidth - len(last_line)) 39 | result.append(last_line) 40 | 41 | return result 42 | 43 | sol = Solution() 44 | words1 = ["This", "is", "an", "example", "of", "text", "justification."] 45 | maxWidth1 = 16 46 | result1 = sol.fullJustify(words1, maxWidth1) 47 | print(result1) 48 | 49 | words2 = ["What","must","be","acknowledgment","shall","be"] 50 | maxWidth2 = 16 51 | result2 = sol.fullJustify(words2, maxWidth2) 52 | print(result2) 53 | 54 | words3 = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"] 55 | maxWidth3 = 20 56 | result3 = sol.fullJustify(words3, maxWidth3) 57 | print(result3) 58 | -------------------------------------------------------------------------------- /generate-paranthesis.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n): 3 | def backtrack(s, left, right): 4 | if len(s) == 2 * n: 5 | result.append(s) 6 | return 7 | 8 | if left < n: 9 | backtrack(s + "(", left + 1, right) 10 | if right < left: 11 | backtrack(s + ")", left, right + 1) 12 | 13 | result = [] 14 | backtrack("", 0, 0) 15 | return result 16 | 17 | # Test cases 18 | solution = Solution() 19 | print(solution.generateParenthesis(3)) # Output: ["((()))","(()())","(())()","()(())","()()()"] 20 | print(solution.generateParenthesis(1)) # Output: ["()"] 21 | -------------------------------------------------------------------------------- /graph.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | n=np.arange(9) 4 | height = [1,8,6,2,5,4,8,3,7] 5 | plt.bar(n,height) 6 | plt.show() -------------------------------------------------------------------------------- /largest_Palindrome_product.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(n): 2 | return str(n) == str(n)[::-1] 3 | 4 | def largest_palindrome(limit): 5 | largest = 0 6 | for i in range(999, 99, -1): 7 | for j in range(999, i - 1, -1): 8 | product = i * j 9 | if product < limit and is_palindrome(product) and product > largest: 10 | largest = product 11 | return largest 12 | 13 | if __name__ == '__main__': 14 | t = int(input("Enter test cases:-").strip()) 15 | for _ in range(t): 16 | n = int(input("Enter a number:-").strip()) 17 | result = largest_palindrome(n) 18 | print(result) 19 | -------------------------------------------------------------------------------- /largest_prime.py: -------------------------------------------------------------------------------- 1 | def largest_prime_factor(number): 2 | # Initialize the largest prime factor to 2 3 | largest = 2 4 | 5 | # Divide the number by 2 until it becomes odd 6 | while number % 2 == 0: 7 | number //= 2 8 | 9 | # Check for prime factors starting from 3 10 | factor = 3 11 | while factor * factor <= number: 12 | while number % factor == 0: 13 | largest = factor 14 | number //= factor 15 | factor += 2 16 | 17 | # If the remaining number is prime 18 | if number > 2: 19 | largest = number 20 | 21 | return largest 22 | 23 | t = int(input("Enter test cases:-").strip()) 24 | for _ in range(t): 25 | n = int(input("Enter a number:-").strip()) 26 | result = largest_prime_factor(n) 27 | print(result) 28 | -------------------------------------------------------------------------------- /letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def letterCombinations(self, digits): 3 | if not digits: 4 | return [] 5 | 6 | digit_to_letters = { 7 | '2': 'abc', '3': 'def', '4': 'ghi', 8 | '5': 'jkl', '6': 'mno', '7': 'pqrs', 9 | '8': 'tuv', '9': 'wxyz' 10 | } 11 | 12 | def backtrack(combination, next_digits): 13 | if len(next_digits) == 0: 14 | result.append(combination) 15 | else: 16 | for letter in digit_to_letters[next_digits[0]]: 17 | backtrack(combination + letter, next_digits[1:]) 18 | 19 | result = [] 20 | backtrack("", digits) 21 | return result 22 | 23 | # Test cases 24 | solution = Solution() 25 | num=input("Enter a num:-") 26 | print(solution.letterCombinations("23")) # Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 27 | print(solution.letterCombinations("")) # Output: [] 28 | print(solution.letterCombinations("2")) # Output: ["a","b","c"] 29 | 30 | #print(solution.letterCombinations(num)) 31 | 32 | -------------------------------------------------------------------------------- /list.py: -------------------------------------------------------------------------------- 1 | X, Y, Z, N = 5,1,2,3 2 | lis = [[x,y,z] for x in range(X + 1) for y in range(Y + 1) for z in range(Z + 1) if x+y+z != N] 3 | print(lis) 4 | 5 | 6 | -------------------------------------------------------------------------------- /longest_valid_braces.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestValidParentheses(self,s): 3 | stack = [] # Use a stack to keep track of the indices of '(' 4 | max_length = 0 # Initialize the maximum length to 0 5 | 6 | for i in range(len(s)): 7 | if s[i] == '(': 8 | stack.append(i) # Push the index of '(' to the stack 9 | else: 10 | if stack and s[stack[-1]] == '(': # If stack is not empty and the top element is '(' 11 | stack.pop() # Pop the top '(' 12 | if not stack: 13 | # If the stack is empty, calculate the length from the beginning of the string 14 | max_length = max(max_length, i + 1) 15 | else: 16 | # Calculate the length from the last unmatched '(' in the stack 17 | max_length = max(max_length, i - stack[-1]) 18 | else: 19 | stack.append(i) # Push the index of ')' to the stack to mark it as invalid 20 | 21 | return max_length 22 | 23 | sol = Solution() 24 | s = "(()" 25 | print("TEST CASE 1:-",s) 26 | out = sol.longestValidParentheses(s) 27 | print("The longest valid parentheses substring is:-",out) 28 | 29 | print("\n") 30 | 31 | s = ")()())" 32 | print("TEST CASE 2:-",s) 33 | out = sol.longestValidParentheses(s) 34 | print("The longest valid parentheses substring is:-",out) 35 | -------------------------------------------------------------------------------- /multiply.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | """ 4 | :type num1: str 5 | :type num2: str 6 | :rtype: str 7 | """ 8 | a=int(num1) 9 | b=int(num2) 10 | c= str(a*b) 11 | return c 12 | 13 | 14 | sol = Solution() 15 | 16 | print("TEST CASE 1:-") 17 | n1 = "2" 18 | n2 = "3" 19 | print("Num 1:-",n1) 20 | print("Num 2:-",n2) 21 | out=sol.multiply(n1,n2) 22 | print("OUTPUT:-",out) 23 | 24 | 25 | print("\nTEST CASE 2:-") 26 | n1 = "123" 27 | n2 = "456" 28 | print("Num 1:-",n1) 29 | print("Num 2:-",n2) 30 | out=sol.multiply(n1,n2) 31 | print("OUTPUT:-",out) -------------------------------------------------------------------------------- /palindrome_partioning.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def partition(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[List[str]] 6 | """ 7 | def is_palindrome(s): 8 | return s == s[::-1] 9 | 10 | def backtrack(start, path): 11 | if start == len(s): 12 | result.append(path[:]) 13 | return 14 | for end in range(start + 1, len(s) + 1): 15 | if is_palindrome(s[start:end]): 16 | path.append(s[start:end]) 17 | backtrack(end, path) 18 | path.pop() 19 | 20 | result = [] 21 | backtrack(0, []) 22 | return result 23 | 24 | # Example usage: 25 | s = "aab" 26 | sol = Solution() 27 | print(sol.partition(s)) # Output: [["a", "a", "b"], ["aa", "b"]] 28 | -------------------------------------------------------------------------------- /paranthesis.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValid(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | stack = [] # Create an empty stack to keep track of opening brackets 8 | 9 | # Define a dictionary to map closing brackets to their corresponding opening brackets 10 | bracket_mapping = {')': '(', '}': '{', ']': '['} 11 | 12 | # Iterate through each character in the input string 13 | for char in s: 14 | # If it's an opening bracket, push it onto the stack 15 | if char in bracket_mapping.values(): 16 | stack.append(char) 17 | # If it's a closing bracket 18 | elif char in bracket_mapping.keys(): 19 | # Check if the stack is empty or the top of the stack doesn't match the current closing bracket 20 | if not stack or stack.pop() != bracket_mapping[char]: 21 | return False # Not valid 22 | else: 23 | return False # Invalid character 24 | 25 | # If the stack is empty, all brackets were valid 26 | return len(stack) == 0 27 | 28 | 29 | s = '(){}[]' 30 | solution = Solution() 31 | is_valid = solution.isValid(s) 32 | print(is_valid) # This will print True for the given input 33 | -------------------------------------------------------------------------------- /pascal.py: -------------------------------------------------------------------------------- 1 | def generate_pascals_triangle_row(n): 2 | row = [1] # Start with the first element as 1 3 | 4 | for i in range(1, n + 1): 5 | next_num = (row[i - 1] * (n - i + 1)) // i 6 | row.append(next_num) 7 | 8 | return row 9 | 10 | # Take input from the user 11 | n = int(input("Enter the level of Pascal's triangle: ")) 12 | 13 | # Generate the nth row of Pascal's triangle 14 | pascal_row = generate_pascals_triangle_row(n) 15 | 16 | # Print the result 17 | print(pascal_row) 18 | -------------------------------------------------------------------------------- /perm.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def permute(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | x,y,z=nums[0],nums[1],nums[2] 8 | lis = [[x,y,z] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1)] 9 | 10 | return lis 11 | 12 | sol = Solution() 13 | 14 | nums = [1,2,3] 15 | res=sol.permute(nums) 16 | 17 | print(res) -------------------------------------------------------------------------------- /qr.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import qrcode 3 | from PIL import ImageTk, Image 4 | 5 | def generate_qr_code(): 6 | data = entry.get() 7 | qr = qrcode.QRCode( 8 | version=1, 9 | error_correction=qrcode.constants.ERROR_CORRECT_L, 10 | box_size=10, 11 | border=4, 12 | ) 13 | qr.add_data(data) 14 | qr.make(fit=True) 15 | 16 | qr_image = qr.make_image(fill_color="black", back_color="white") 17 | 18 | img = ImageTk.PhotoImage(qr_image) 19 | qr_code_image.config(image=img) 20 | qr_code_image.image = img 21 | 22 | # Create main app 23 | app = tk.Tk() 24 | app.title("QR Code Generator") 25 | app.geometry("360x480") # Adjust the window size as needed 26 | 27 | # Set a background color 28 | app.configure(bg="#E0E0E0") 29 | 30 | # Create a label with Android-like style 31 | label = tk.Label( 32 | app, 33 | text="Enter the data:", 34 | font=("Roboto", 16), 35 | bg="#E0E0E0", # Use a light gray color 36 | ) 37 | label.pack(pady=10) 38 | 39 | # Create an entry field 40 | entry = tk.Entry( 41 | app, 42 | font=("Roboto", 14), 43 | bg="white", 44 | ) 45 | entry.pack(fill=tk.BOTH, padx=20) 46 | 47 | # Create a button with Android-like style 48 | generate_button = tk.Button( 49 | app, 50 | text="Generate QR Code", 51 | font=("Roboto", 14), 52 | bg="#6200EE", # Use a deep purple color 53 | fg="white", 54 | command=generate_qr_code, 55 | ) 56 | generate_button.pack(pady=10) 57 | 58 | # Create an image label 59 | qr_code_image = tk.Label(app, bg="#E0E0E0") 60 | qr_code_image.pack() 61 | 62 | # Run the app 63 | app.mainloop() 64 | -------------------------------------------------------------------------------- /questions.txt: -------------------------------------------------------------------------------- 1 | Question 1 What is the correct way to declare a variable in Python? 2 | a) var x = 5 3 | b) x = 5 4 | c) int x = 5 5 | d) declare x = 5 6 | Correct Answer: b 7 | 8 | Question 2 Which of the following is a Python data type? 9 | a) Integer 10 | b) String 11 | c) Float 12 | d) All of the above 13 | Correct Answer: d 14 | 15 | Question 3 How do you write a comment in Python? 16 | a) // This is a comment 17 | b) /* This is a comment */ 18 | c) # This is a comment 19 | d) 20 | Correct Answer: c 21 | 22 | Question 4 What is the correct syntax to create a function in Python? 23 | a) create my_function(): 24 | b) def my_function(): 25 | c) function my_function(): 26 | d) my_function(): 27 | Correct Answer: b 28 | 29 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashksaini-coder/Leetcode-Python-Solutions/37c627f9d15d1053fa6661db83786eafe1d86596/requirements.txt -------------------------------------------------------------------------------- /reverse_node_kgroup.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution(object): 8 | def reverseKGroup(self, head, k): 9 | """ 10 | :type head: ListNode 11 | :type k: int 12 | :rtype: ListNode 13 | """ 14 | def reverse_list(head, k): 15 | prev = None 16 | current = head 17 | while k > 0: 18 | next_node = current.next 19 | current.next = prev 20 | prev = current 21 | current = next_node 22 | k -= 1 23 | return prev 24 | 25 | def count_nodes(node): 26 | count = 0 27 | while node: 28 | count += 1 29 | node = node.next 30 | return count 31 | 32 | # Calculate the length of the linked list 33 | length = count_nodes(head) 34 | 35 | # Initialize a dummy node before the head 36 | dummy = ListNode(0) 37 | dummy.next = head 38 | prev_group_end = dummy 39 | while length >= k: 40 | group_start = prev_group_end.next 41 | group_end = group_start 42 | for _ in range(k - 1): 43 | group_end = group_end.next 44 | 45 | next_group_start = group_end.next 46 | group_end.next = None 47 | 48 | # Reverse the current group and connect it back 49 | prev_group_end.next = reverse_list(group_start, k) 50 | group_start.next = next_group_start 51 | 52 | prev_group_end = group_start 53 | length -= k 54 | 55 | return dummy.next 56 | 57 | sol = Solution() 58 | #test case 1 59 | l=[1,2,3,4,5] 60 | k = 2 61 | print("CASE-1\nList:-",l,"\nk:-",k) 62 | #test case 2 63 | out = sol.reverseKGroup(l,k) -------------------------------------------------------------------------------- /rotate_matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: list[list[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | matrix[:] = zip(*matrix[::-1]) 7 | 8 | sol=Solution() 9 | 10 | #test case 1 11 | matrix = [[1,2,3],[4,5,6],[7,8,9]] 12 | print("Matrix:-\n") 13 | print("[[1,2,3]","\n","[4,5,6]","\n","[7,8,9]]") 14 | 15 | # code is modified to fit into python3 version 16 | -------------------------------------------------------------------------------- /runner.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | # Take user input for the array 3 | n = int(input("Enter the number of elements in the array: ")) 4 | arr = list(map(int, input("Enter the elements of the array separated by spaces: ").split())) 5 | 6 | # Initialize variables to keep track of the first and second maximum 7 | first_max = float('-inf') 8 | second_max = float('-inf') 9 | 10 | # Iterate through the array to find the first and second maximum elements 11 | for num in arr: 12 | if num > first_max: 13 | second_max = first_max 14 | first_max = num 15 | elif num > second_max and num != first_max: 16 | second_max = num 17 | 18 | # Print the second maximum element 19 | if second_max == float('-inf'): 20 | print("There is no second maximum element in the array.") 21 | else: 22 | print("The second maximum element is:", second_max) 23 | -------------------------------------------------------------------------------- /search_insert.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchInsert(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | left, right = 0, len(nums) - 1 9 | 10 | while left <= right: 11 | mid = left + (right - left) // 2 12 | 13 | if nums[mid] == target: 14 | return mid 15 | elif nums[mid] < target: 16 | left = mid + 1 17 | else: 18 | right = mid - 1 19 | 20 | # If the target is not found, 'left' will be the correct insertion index. 21 | return left 22 | 23 | sol = Solution() 24 | nums = [1,3,5,6] 25 | target = 5 26 | 27 | out = sol.searchInsert(nums,target) 28 | print(out) 29 | 30 | # Given a sorted array of distinct integers and a target value, return the index if the target is found. 31 | # If not, return the index where it would be if it were inserted in order. -------------------------------------------------------------------------------- /search_matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchMatrix(self, matrix, target): 3 | """ 4 | :type matrix: List[List[int]] 5 | :type target: int 6 | :rtype: bool 7 | """ 8 | if not matrix or not matrix[0]: 9 | return False 10 | 11 | rows, cols = len(matrix), len(matrix[0]) 12 | row, col = 0, cols - 1 # Start from the top-right corner 13 | 14 | while row < rows and col >= 0: 15 | if matrix[row][col] == target: 16 | return True 17 | elif matrix[row][col] < target: 18 | row += 1 # Move down if the current value is smaller 19 | else: 20 | col -= 1 # Move left if the current value is larger 21 | 22 | return False 23 | 24 | l = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] 25 | n = 20 26 | 27 | sol = Solution() 28 | result = sol.searchMatrix(l, n) 29 | print(result) 30 | -------------------------------------------------------------------------------- /smallest_multiple.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | while b: 3 | a, b = b, a % b 4 | return a 5 | 6 | def lcm(a, b): 7 | return a * b // gcd(a, b) 8 | 9 | def smallest_multiple(limit): 10 | result = 1 11 | for i in range(1, limit + 1): 12 | result = lcm(result, i) 13 | return result 14 | 15 | if __name__ == '__main__': 16 | t = int(input("Enter test cases:-").strip()) 17 | for _ in range(t): 18 | n = int(input("Enter a number:-").strip()) 19 | result = smallest_multiple(n) 20 | print(result) 21 | -------------------------------------------------------------------------------- /stack_using-queues.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class MyStack: 4 | 5 | def __init__(self): 6 | self.queue1 = deque() 7 | self.queue2 = deque() 8 | 9 | def push(self, x): 10 | """ 11 | :type x: int 12 | :rtype: None 13 | """ 14 | # Push the new element onto queue1 15 | self.queue1.append(x) 16 | 17 | def pop(self): 18 | """ 19 | :rtype: int 20 | """ 21 | # Move all elements from queue1 to queue2 except the last one 22 | while len(self.queue1) > 1: 23 | self.queue2.append(self.queue1.popleft()) 24 | 25 | # The last element in queue1 is the one to be removed (top of the stack) 26 | top_element = self.queue1.popleft() 27 | 28 | # Swap the names of queue1 and queue2 to make queue2 empty 29 | self.queue1, self.queue2 = self.queue2, self.queue1 30 | 31 | return top_element 32 | 33 | def top(self): 34 | """ 35 | :rtype: int 36 | """ 37 | # This is similar to the pop operation, but we don't remove the element 38 | while len(self.queue1) > 1: 39 | self.queue2.append(self.queue1.popleft()) 40 | 41 | # The last element in queue1 is the top of the stack 42 | top_element = self.queue1[0] 43 | 44 | # Move the element to queue2 for consistency 45 | self.queue2.append(self.queue1.popleft()) 46 | 47 | # Swap the names of queue1 and queue2 to make queue2 empty 48 | self.queue1, self.queue2 = self.queue2, self.queue1 49 | 50 | return top_element 51 | 52 | def empty(self): 53 | """ 54 | :rtype: bool 55 | """ 56 | # Queue1 will be empty if and only if the stack is empty 57 | return not bool(self.queue1) 58 | 59 | # Example usage: 60 | myStack = MyStack() 61 | myStack.push(1) 62 | myStack.push(2) 63 | print(myStack.top()) # Output: 2 64 | print(myStack.pop()) # Output: 2 65 | print(myStack.empty()) # Output: False 66 | -------------------------------------------------------------------------------- /string to integer(atoi).py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def myAtoi(self, s): 3 | s = s.lstrip() 4 | 5 | if not s: 6 | return 0 7 | 8 | sign = 1 9 | 10 | if s[0] in ('+', '-'): 11 | sign = -1 if s[0] == '-' else 1 12 | s = s[1:] 13 | 14 | result = 0 15 | for char in s: 16 | if char.isdigit(): 17 | result = result * 10 + int(char) 18 | else: 19 | break 20 | 21 | result = sign * result 22 | result = max(min(result, 2**31 - 1), -2**31) 23 | 24 | return result 25 | 26 | # Create an instance of the Solution class 27 | solution = Solution() 28 | 29 | # Pass the input string to the myAtoi method 30 | input_str = "42" # Replace this with your input string 31 | output = solution.myAtoi(input_str) 32 | 33 | # Print the result 34 | print(output) 35 | -------------------------------------------------------------------------------- /sudoku_solver.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveSudoku(self, board): 3 | def is_valid(num, row, col): 4 | # Check if 'num' is valid in the current row, column, and subgrid 5 | for i in range(9): 6 | if board[row][i] == num or board[i][col] == num or board[row // 3 * 3 + i // 3][col // 3 * 3 + i % 3] == num: 7 | return False 8 | return True 9 | 10 | def backtrack(row, col): 11 | if row == 9: 12 | return True # We've filled all rows successfully 13 | 14 | if col == 9: 15 | return backtrack(row + 1, 0) # Move to the next row 16 | 17 | if board[row][col] != '.': 18 | return backtrack(row, col + 1) # Cell is already filled, move to the next 19 | 20 | for num in map(str, range(1, 10)): 21 | if is_valid(num, row, col): 22 | board[row][col] = num 23 | if backtrack(row, col + 1): 24 | return True 25 | board[row][col] = '.' # If the current path doesn't lead to a solution, backtrack 26 | 27 | return False # No valid number found, need to backtrack further 28 | 29 | backtrack(0, 0) # Start solving from the top-left cell 30 | return board 31 | 32 | # Example Sudoku board 33 | board = [["5","3",".",".","7",".",".",".","."], 34 | ["6",".",".","1","9","5",".",".","."], 35 | [".","9","8",".",".",".",".","6","."], 36 | ["8",".",".",".","6",".",".",".","3"], 37 | ["4",".",".","8",".","3",".",".","1"], 38 | ["7",".",".",".","2",".",".",".","6"], 39 | [".","6",".",".",".",".","2","8","."], 40 | [".",".",".","4","1","9",".",".","5"], 41 | [".",".",".",".","8",".",".","7","9"]] 42 | 43 | solution = Solution() 44 | print("Original Board") 45 | for row in board: 46 | print(row) 47 | 48 | print("\n") 49 | print("Solved Board") 50 | print("\n") 51 | solved_board = solution.solveSudoku(board) 52 | for row in solved_board: 53 | print(row) 54 | -------------------------------------------------------------------------------- /sum_of_15.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | t = int(input("enter test cases:-")) 3 | for _ in range(t): 4 | n = int(input("enter a number")) 5 | sum_3 = (3 * ((n - 1) // 3) * (((n - 1) // 3) + 1)) // 2 6 | sum_5 = (5 * ((n - 1) // 5) * (((n - 1) // 5) + 1)) // 2 7 | sum_15 = (15 * ((n - 1) // 15) * (((n - 1) // 15) + 1)) // 2 8 | result = sum_3 + sum_5 - sum_15 9 | print(result) 10 | -------------------------------------------------------------------------------- /sum_of_square.py: -------------------------------------------------------------------------------- 1 | t=int(input("Enter test cases:-")) 2 | for _ in range(t): 3 | n=int(input("Enter a number:-")) 4 | sum=0 5 | sum_2=0 6 | for _ in range(n+1): 7 | sum += _ 8 | 9 | 10 | for _ in range(n+1): 11 | sum_2 += _**2 12 | 13 | 14 | 15 | square_of_sum = sum**2 16 | sum_of_square = sum_2 17 | 18 | result = square_of_sum - sum_of_square 19 | print(square_of_sum) 20 | print(sum_of_square) 21 | print(result) 22 | -------------------------------------------------------------------------------- /swap_nodes.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode(object): 3 | def __init__(self, val=0, next=None): 4 | self.val = val 5 | self.next = next 6 | 7 | class Solution(object): 8 | def swapPairs(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | # Initialize a dummy node before the head 14 | dummy = ListNode(0) 15 | dummy.next = head 16 | current = dummy 17 | 18 | while current.next and current.next.next: 19 | # Nodes to be swapped 20 | first_node = current.next 21 | second_node = current.next.next 22 | 23 | # Swapping 24 | current.next = second_node 25 | first_node.next = second_node.next 26 | second_node.next = first_node 27 | 28 | # Move the pointer to the next pair 29 | current = first_node 30 | 31 | return dummy.next 32 | 33 | # Define a separate print_linked_list function 34 | def print_linked_list(head): 35 | current = head 36 | while current: 37 | print(current.val, end=" -> ") 38 | current = current.next 39 | print("None") 40 | 41 | # Example usage 42 | # Create linked list: 1 -> 2 -> 3 -> 4 43 | head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) 44 | print("ORIGINAL LIST:") 45 | print_linked_list(head) 46 | 47 | # Print the swapped linked list: 2 -> 1 -> 4 -> 3 48 | solution = Solution() 49 | swapped_head = solution.swapPairs(head) 50 | print("\nSWAPPED LIST:") 51 | print_linked_list(swapped_head) 52 | -------------------------------------------------------------------------------- /trap.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def trap(self,height): 3 | if not height: 4 | return 0 5 | 6 | left, right = 0, len(height) - 1 7 | left_max, right_max = 0, 0 8 | trapped_water = 0 9 | 10 | while left < right: 11 | if height[left] < height[right]: 12 | if height[left] >= left_max: 13 | left_max = height[left] 14 | else: 15 | trapped_water += left_max - height[left] 16 | left += 1 17 | else: 18 | if height[right] >= right_max: 19 | right_max = height[right] 20 | else: 21 | trapped_water += right_max - height[right] 22 | right -= 1 23 | 24 | return trapped_water 25 | 26 | sol = Solution() 27 | 28 | # Example 1 29 | height1 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] 30 | result1 = sol.trap(height1) 31 | 32 | # Example 2 33 | height2 = [4, 2, 0, 3, 2, 5] 34 | result2 = sol.trap(height2) 35 | 36 | print(f"Trapped Water for Example 1: {result1} units") 37 | print(f"Trapped Water for Example 2: {result2} units") 38 | -------------------------------------------------------------------------------- /valid_sudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board): 3 | def is_valid_subbox(row, col): 4 | seen = set() 5 | for i in range(row, row + 3): 6 | for j in range(col, col + 3): 7 | if board[i][j] != ".": 8 | if board[i][j] in seen: 9 | return False 10 | seen.add(board[i][j]) 11 | return True 12 | 13 | for i in range(9): 14 | row_seen = set() 15 | col_seen = set() 16 | for j in range(9): 17 | # Check rows 18 | if board[i][j] != ".": 19 | if board[i][j] in row_seen: 20 | return False 21 | row_seen.add(board[i][j]) 22 | 23 | # Check columns 24 | if board[j][i] != ".": 25 | if board[j][i] in col_seen: 26 | return False 27 | col_seen.add(board[j][i]) 28 | 29 | # Check sub-boxes 30 | if i % 3 == 0: 31 | for j in range(0, 9, 3): 32 | if not is_valid_subbox(i, j): 33 | return False 34 | 35 | return True 36 | 37 | # Example boards 38 | board1 = [["5","3",".",".","7",".",".",".","."], 39 | ["6",".",".","1","9","5",".",".","."], 40 | [".","9","8",".",".",".",".","6","."], 41 | ["8",".",".",".","6",".",".",".","3"], 42 | ["4",".",".","8",".","3",".",".","1"], 43 | ["7",".",".",".","2",".",".",".","6"], 44 | [".","6",".",".",".",".","2","8","."], 45 | [".",".",".","4","1","9",".",".","5"], 46 | [".",".",".",".","8",".",".","7","9"]] 47 | 48 | board2 = [["8","3",".",".","7",".",".",".","."], 49 | ["6",".",".","1","9","5",".",".","."], 50 | [".","9","8",".",".",".",".","6","."], 51 | ["8",".",".",".","6",".",".",".","3"], 52 | ["4",".",".","8",".","3",".",".","1"], 53 | ["7",".",".",".","2",".",".",".","6"], 54 | [".","6",".",".",".",".","2","8","."], 55 | [".",".",".","4","1","9",".",".","5"], 56 | [".",".",".",".","8",".",".","7","9"]] 57 | 58 | solution = Solution() 59 | print(solution.isValidSudoku(board1)) # Output: True 60 | print(solution.isValidSudoku(board2)) # Output: False 61 | --------------------------------------------------------------------------------