├── My_Learning ├── Day_72 │ ├── ques │ └── LeftLeave.py ├── Day_61 │ ├── ques │ └── SwapNodes.py ├── Day_97 │ ├── ques │ └── Combinations.py ├── Day_92 │ ├── ques │ └── Heap.py ├── Day_23 │ ├── ques │ └── noOfOnes.py ├── Day_79 │ ├── ques │ └── BinaryTree.py ├── Day_48 │ ├── ques │ └── ReorderList.py ├── Day_32 │ ├── PowerOfTwo.py │ └── ques ├── Day_20 │ ├── ValidNumber.py │ └── ques ├── Day_70 │ ├── ques │ └── BinaryTree.py ├── Day_54 │ ├── ques │ └── RightInterval.py ├── Day_31 │ ├── GrayCode.py │ └── ques ├── Day_90 │ ├── ques │ └── ValidateBST.py ├── Day_16 │ ├── ques │ └── Pascals_triangle.py ├── Day_34 │ ├── Missing.py │ └── ques ├── Day_94 │ ├── ques │ └── Sorted List.py ├── Day_50 │ ├── ques │ └── LargestNumber.py ├── Day_84 │ ├── ques │ └── Add_Binary.py ├── Day_12 │ ├── ques │ └── Moves_Zero.py ├── Day_88 │ ├── ques │ └── +veNumber.py ├── Day_8 │ ├── Concatenation_of_Array.py │ └── Dictionary ├── Day_85 │ ├── ques │ └── InterleavingString.py ├── Day_15 │ ├── ques │ └── SubArraySum.py ├── Day_99 │ ├── ques │ └── Calculator.py ├── Day_81 │ ├── RotateArray.py │ └── ques ├── Day_86 │ ├── Buy&Sell.py │ └── ques ├── Day_83 │ ├── ques │ └── MaxSubArray.py ├── Day_93 │ ├── ques │ └── Palindrome.py ├── Day_17 │ ├── LengthOfLastWord.py │ └── ques ├── Day_51 │ ├── HIndex.py │ └── ques ├── Day_10 │ ├── ques │ └── Contains_Duplicate_2.py ├── Day_68 │ ├── ques │ └── Permutation.py ├── Day_73 │ ├── ques │ └── BeautifulArray.py ├── Day_7 │ ├── Valid_Palindrome.py │ └── Tuples ├── Day_39 │ ├── peakElement.py │ └── ques ├── Day_11 │ ├── ques │ └── Reverse_String.py ├── Day_18 │ ├── ques │ └── PermutationSequence.py ├── Day_80 │ ├── ques │ └── Linkedlist.py ├── Day_64 │ ├── ques │ └── CountGoodNumbers.py ├── Day_22 │ ├── ques │ └── wordFrequency.py ├── Day_63 │ ├── ques │ └── RemoveNodes.py ├── Day_5 │ ├── Valid_Anagram.py │ └── List ├── Day_41 │ ├── ques │ └── 4Sum.py ├── Day_74 │ ├── Roam_2_integer.py │ └── ques ├── Day_46 │ ├── ques │ └── 4Sum.py ├── Day_26 │ ├── WordBreak.py │ └── ques ├── Day_56 │ ├── ZigZag.py │ └── ques ├── Day_19 │ ├── RegularExpressionMatching.py │ └── ques ├── Day_91 │ ├── ques │ └── ScrambleString.py ├── Day_49 │ ├── Zigzag_Conversion.py │ └── ques ├── Day_6 │ ├── Group_Anagram.py │ └── Sets ├── Day_21 │ ├── ScrambleString.py │ └── ques ├── Day_3 │ ├── two_sum.py │ └── Arrays ├── Day_77 │ ├── ques │ └── CoinChange.py ├── Day_95 │ ├── ques │ └── Queue.py ├── Day_4 │ ├── Contains_Duplicate.py │ └── Function ├── Day_44 │ ├── PlusOne.py │ └── ques ├── Day_45 │ ├── ques │ └── 3SumClosest.py ├── Day_42 │ ├── ques │ └── RotateArray.py ├── Day_65 │ ├── ques │ └── Search_inserted_postion.py ├── Day_30 │ ├── flowerbed.py │ └── ques ├── Day_60 │ ├── ques │ └── 3Sum_Closet.py ├── Day_38 │ ├── Decode_string.py │ └── ques.txt ├── Day_40 │ ├── ques │ └── CombinationSum.py ├── Day_28 │ ├── ques │ └── isomorphic.py ├── Day_9 │ ├── Best_time_to_Sell&Buy_Stocks.py │ └── Lamda ├── Day_62 │ ├── ques │ └── Multiple_Strings.py ├── Day_55 │ ├── AssignCookies.py │ └── ques ├── Day_33 │ └── PosionDuration.py ├── Day_75 │ ├── ques │ └── LinkedList.py ├── Day_24 │ ├── ques │ └── mergeKSortedList.py ├── Day_96 │ ├── ques │ └── HashMap.py ├── Day_2 │ ├── guessing_game.py │ └── basic ├── Day_52 │ ├── TaskScheduler.py │ └── ques ├── Day_57 │ ├── ques │ └── AccountsMerge.py ├── Day_14 │ ├── Merge_Sorted_Array.py │ └── ques.txt ├── Day_47 │ ├── ques │ └── InsertInterval.py ├── Day_69 │ ├── Jump_Game.py │ └── ques ├── Day_82 │ ├── ques │ └── RestoreIP.py ├── Day_76 │ ├── ques │ └── SortedMatrix.py ├── Day_25 │ ├── Candy.py │ └── ques ├── Day_29 │ ├── LRUCache.py │ └── ques ├── Day_35 │ ├── ques │ └── Longest_Repeating_Character_Replacement.py ├── Day_59 │ ├── combinationSum.py │ └── ques ├── Day_13 │ ├── Removes_Duplicates.py │ └── ques ├── Day_98 │ ├── Integer.py │ └── ques ├── Day_71 │ ├── String_2_integer.py │ └── ques ├── Day_78 │ ├── BagofTokens.py │ └── ques ├── Day_27 │ ├── 3_sum.py │ └── ques ├── Day_89 │ ├── Wildcard_matching.py │ └── ques ├── Day_67 │ ├── ques │ └── CircularDequeue.py ├── Day_58 │ ├── ques │ └── Divide_integer.py ├── Day_43 │ ├── DesignBitset.py │ └── ques ├── Day_37 │ ├── MinStack.py │ └── ques ├── Day_87 │ ├── VersionNumber.py │ └── ques ├── Day_53 │ ├── ques │ └── AccountsMerge.py ├── Day_1 ├── Day_36 │ ├── WordLadder.py │ └── ques └── Day_66 │ ├── ques │ └── CircularQueue.py └── README.md /My_Learning/Day_72/ques: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, return the sum of all left leaves. 2 | 3 | A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. 4 | -------------------------------------------------------------------------------- /My_Learning/Day_61/ques: -------------------------------------------------------------------------------- 1 | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 2 | -------------------------------------------------------------------------------- /My_Learning/Day_97/ques: -------------------------------------------------------------------------------- 1 | Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. 2 | 3 | You may return the answer in any order. 4 | 5 | Example : 6 | 7 | Input: n = 4, k = 2 8 | Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 9 | -------------------------------------------------------------------------------- /My_Learning/Day_92/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 2 | 3 | Example 1: 4 | Input: nums = [1,1,1,2,2,3], k = 2 5 | Output: [1,2] 6 | 7 | Example 2: 8 | Input: nums = [1], k = 1 9 | Output: [1] 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 100DaysOfCode_Python 2 | 🚀 Embarking on the #100DaysOfCode Python challenge! Join me on this coding journey as I commit to coding every day for the next 100 days. From Python basics to advanced projects, expect a diverse range of code exploration. Let's level up our Python skills together! 💻 3 | -------------------------------------------------------------------------------- /My_Learning/Day_23/ques: -------------------------------------------------------------------------------- 1 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 2 | 3 | Example 1: 4 | 5 | Input: n = 13 6 | Output: 6 7 | Example 2: 8 | 9 | Input: n = 0 10 | Output: 0 11 | 12 | 13 | Constraints: 14 | 15 | 0 <= n <= 109 16 | -------------------------------------------------------------------------------- /My_Learning/Day_79/ques: -------------------------------------------------------------------------------- 1 | Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. 2 | 3 | Example 1: 4 | Input: n = 3 5 | Output: 5 6 | 7 | Example 2: 8 | Input: n = 1 9 | Output: 1 10 | 11 | Constraints: 12 | 1 <= n <= 19 13 | -------------------------------------------------------------------------------- /My_Learning/Day_48/ques: -------------------------------------------------------------------------------- 1 | You are given the head of a singly linked-list. The list can be represented as: 2 | 3 | L0 → L1 → … → Ln - 1 → Ln 4 | Reorder the list to be on the following form: 5 | 6 | L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 7 | You may not modify the values in the list's nodes. Only nodes themselves may be changed. 8 | -------------------------------------------------------------------------------- /My_Learning/Day_32/PowerOfTwo.py: -------------------------------------------------------------------------------- 1 | def isPowerOfTwo(n): 2 | if n <= 0: 3 | return False 4 | return n & (n - 1) == 0 5 | 6 | # Take user input for the integer n 7 | n = int(input("Enter an integer: ")) 8 | 9 | # Check if n is a power of two 10 | result = isPowerOfTwo(n) 11 | print("Output:", result) 12 | -------------------------------------------------------------------------------- /My_Learning/Day_20/ValidNumber.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def isNumber(s): 4 | pattern = r'^[-+]?\d*\.?\d*(?:[eE][-+]?\d+)?$' 5 | return bool(re.match(pattern, s.strip())) 6 | 7 | # Take user input for the string 8 | s = input("Enter a string: ") 9 | 10 | # Check if the input string is a valid number 11 | result = isNumber(s) 12 | print("Output:", result) 13 | 14 | -------------------------------------------------------------------------------- /My_Learning/Day_23/noOfOnes.py: -------------------------------------------------------------------------------- 1 | def countDigitOne(n): 2 | count = 0 3 | for i in range(1, n + 1): 4 | count += str(i).count('1') 5 | return count 6 | 7 | # Take user input for the integer n 8 | n = int(input("Enter an integer n: ")) 9 | 10 | # Count the total number of digit 1 11 | result = countDigitOne(n) 12 | print("Output:", result) 13 | -------------------------------------------------------------------------------- /My_Learning/Day_70/ques: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 2 | 3 | Example 1: 4 | Input: root = [3,9,20,null,null,15,7] 5 | Output: [[3],[9,20],[15,7]] 6 | 7 | Example 2: 8 | Input: root = [1] 9 | Output: [[1]] 10 | 11 | Example 3: 12 | Input: root = [] 13 | Output: [] 14 | 15 | -------------------------------------------------------------------------------- /My_Learning/Day_54/ques: -------------------------------------------------------------------------------- 1 | You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. 2 | 3 | The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. 4 | 5 | Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. 6 | -------------------------------------------------------------------------------- /My_Learning/Day_31/GrayCode.py: -------------------------------------------------------------------------------- 1 | def grayCode(n): 2 | gray_sequence = [0] 3 | for i in range(1, 2 ** n): 4 | gray_sequence.append(i ^ (i >> 1)) 5 | return gray_sequence 6 | 7 | # Take user input for the value of n 8 | n = int(input("Enter the value of n: ")) 9 | 10 | # Generate the gray code sequence 11 | result = grayCode(n) 12 | print("Output:", result) 13 | 14 | -------------------------------------------------------------------------------- /My_Learning/Day_90/ques: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 2 | 3 | A valid BST is defined as follows: 4 | The left subtree of a node contains only nodes with keys less than the node's key. 5 | The right subtree of a node contains only nodes with keys greater than the node's key. 6 | Both the left and right subtrees must also be binary search trees. 7 | 8 | -------------------------------------------------------------------------------- /My_Learning/Day_16/ques: -------------------------------------------------------------------------------- 1 | Given an integer numRows, return the first numRows of Pascal's triangle. 2 | 3 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: numRows = 5 11 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 12 | Example 2: 13 | 14 | Input: numRows = 1 15 | Output: [[1]] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= numRows <= 30 21 | -------------------------------------------------------------------------------- /My_Learning/Day_34/Missing.py: -------------------------------------------------------------------------------- 1 | def missingNumber(nums): 2 | n = len(nums) 3 | expected_sum = n * (n + 1) // 2 4 | actual_sum = sum(nums) 5 | return expected_sum - actual_sum 6 | 7 | # Take user input for the array nums 8 | nums = list(map(int, input("Enter the numbers in the array separated by space: ").split())) 9 | 10 | # Find the missing number 11 | result = missingNumber(nums) 12 | print("Output:", result) 13 | -------------------------------------------------------------------------------- /My_Learning/Day_94/ques: -------------------------------------------------------------------------------- 1 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. 2 | 3 | Merge all the linked-lists into one sorted linked-list and return it. 4 | 5 | Example : 6 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 7 | Output: [1,1,2,3,4,4,5,6] 8 | Explanation: The linked-lists are: 9 | [ 10 | 1->4->5, 11 | 1->3->4, 12 | 2->6 13 | ] 14 | merging them into one sorted list: 15 | 1->1->2->3->4->4->5->6 16 | -------------------------------------------------------------------------------- /My_Learning/Day_50/ques: -------------------------------------------------------------------------------- 1 | Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. 2 | 3 | Since the result may be very large, so you need to return a string instead of an integer. 4 | Example 1: 5 | 6 | Input: nums = [10,2] 7 | Output: "210" 8 | Example 2: 9 | 10 | Input: nums = [3,30,34,5,9] 11 | Output: "9534330" 12 | 13 | Constraints: 14 | 15 | 1 <= nums.length <= 100 16 | 0 <= nums[i] <= 109 17 | -------------------------------------------------------------------------------- /My_Learning/Day_84/ques: -------------------------------------------------------------------------------- 1 | Given two binary strings a and b, return their sum as a binary string. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: a = "11", b = "1" 8 | Output: "100" 9 | Example 2: 10 | 11 | Input: a = "1010", b = "1011" 12 | Output: "10101" 13 | 14 | 15 | Constraints: 16 | 17 | 1 <= a.length, b.length <= 104 18 | a and b consist only of '0' or '1' characters. 19 | Each string does not contain leading zeros except for the zero itself. 20 | -------------------------------------------------------------------------------- /My_Learning/Day_12/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 2 | 3 | Note that you must do this in-place without making a copy of the array. 4 | 5 | Example 1: 6 | 7 | Input: nums = [0,1,0,3,12] 8 | Output: [1,3,12,0,0] 9 | Example 2: 10 | 11 | Input: nums = [0] 12 | Output: [0] 13 | 14 | Constraints: 15 | 16 | 1 <= nums.length <= 104 17 | -231 <= nums[i] <= 231 - 1 18 | -------------------------------------------------------------------------------- /My_Learning/Day_88/ques: -------------------------------------------------------------------------------- 1 | Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums. 2 | 3 | You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. 4 | 5 | Example 1: 6 | Input: nums = [1,2,0] 7 | Output: 3 8 | Explanation: The numbers in the range [1,2] are all in the array. 9 | 10 | Example 2: 11 | Input: nums = [3,4,-1,1] 12 | Output: 2 13 | Explanation: 1 is in the array but 2 is missing. 14 | -------------------------------------------------------------------------------- /My_Learning/Day_32/ques: -------------------------------------------------------------------------------- 1 | Given an integer n, return true if it is a power of two. Otherwise, return false. 2 | 3 | An integer n is a power of two, if there exists an integer x such that n == 2x. 4 | 5 | Example 1: 6 | 7 | Input: n = 1 8 | Output: true 9 | Explanation: 20 = 1 10 | Example 2: 11 | 12 | Input: n = 16 13 | Output: true 14 | Explanation: 24 = 16 15 | Example 3: 16 | 17 | Input: n = 3 18 | Output: false 19 | 20 | Constraints: 21 | 22 | -231 <= n <= 231 - 1 23 | -------------------------------------------------------------------------------- /My_Learning/Day_8/Concatenation_of_Array.py: -------------------------------------------------------------------------------- 1 | def concatenate_array(nums): 2 | n = len(nums) 3 | ans = nums + nums # Concatenate the array with itself 4 | return ans 5 | 6 | # Take user input for the array 7 | user_input = input("Enter integers separated by space: ") 8 | nums = list(map(int, user_input.split())) 9 | 10 | # Create the concatenated array 11 | result = concatenate_array(nums) 12 | 13 | # Display the result 14 | print("Output:", result) 15 | -------------------------------------------------------------------------------- /My_Learning/Day_85/ques: -------------------------------------------------------------------------------- 1 | Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. 2 | 3 | An interleaving of two strings s and t is a configuration where s and t are divided into n and m 4 | substrings respectively, such that: 5 | s = s1 + s2 + ... + sn 6 | t = t1 + t2 + ... + tm 7 | |n - m| <= 1 8 | The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... 9 | Note: a + b is the concatenation of strings a and b. 10 | -------------------------------------------------------------------------------- /My_Learning/Day_15/ques: -------------------------------------------------------------------------------- 1 | Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 2 | 3 | A subarray is a contiguous non-empty sequence of elements within an array. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [1,1,1], k = 2 10 | Output: 2 11 | Example 2: 12 | 13 | Input: nums = [1,2,3], k = 3 14 | Output: 2 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= nums.length <= 2 * 104 20 | -1000 <= nums[i] <= 1000 21 | -107 <= k <= 107 22 | -------------------------------------------------------------------------------- /My_Learning/Day_99/ques: -------------------------------------------------------------------------------- 1 | Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. 2 | 3 | Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). 4 | 5 | Example 1: 6 | 7 | Input: s = "1 + 1" 8 | Output: 2 9 | Example 2: 10 | 11 | Input: s = " 2-1 + 2 " 12 | Output: 3 13 | Example 3: 14 | 15 | Input: s = "(1+(4+5+2)-3)+(6+8)" 16 | Output: 23 17 | -------------------------------------------------------------------------------- /My_Learning/Day_81/RotateArray.py: -------------------------------------------------------------------------------- 1 | def rotate(nums, k): 2 | # Calculate effective rotation amount 3 | k = k % len(nums) 4 | 5 | # Rotate the array using array slicing 6 | nums[:] = nums[-k:] + nums[:-k] 7 | 8 | # Test cases 9 | nums1 = [1, 2, 3, 4, 5, 6, 7] 10 | k1 = 3 11 | rotate(nums1, k1) 12 | print(nums1) # Output: [5, 6, 7, 1, 2, 3, 4] 13 | 14 | nums2 = [-1, -100, 3, 99] 15 | k2 = 2 16 | rotate(nums2, k2) 17 | print(nums2) # Output: [3, 99, -1, -100] 18 | -------------------------------------------------------------------------------- /My_Learning/Day_86/Buy&Sell.py: -------------------------------------------------------------------------------- 1 | def maxProfit(prices): 2 | if not prices or len(prices) == 1: 3 | return 0 4 | 5 | min_price = float('inf') 6 | max_profit = 0 7 | 8 | for price in prices: 9 | min_price = min(min_price, price) 10 | max_profit = max(max_profit, price - min_price) 11 | 12 | return max_profit 13 | 14 | # Test cases 15 | print(maxProfit([7,1,5,3,6,4])) # Output: 5 16 | print(maxProfit([7,6,4,3,1])) # Output: 0 17 | -------------------------------------------------------------------------------- /My_Learning/Day_83/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find the subarray with the largest sum, and return its sum. 2 | 3 | Example 1: 4 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 5 | Output: 6 6 | Explanation: The subarray [4,-1,2,1] has the largest sum 6. 7 | 8 | Example 2: 9 | Input: nums = [1] 10 | Output: 1 11 | Explanation: The subarray [1] has the largest sum 1. 12 | 13 | Example 3: 14 | Input: nums = [5,4,-1,7,8] 15 | Output: 23 16 | Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. 17 | -------------------------------------------------------------------------------- /My_Learning/Day_93/ques: -------------------------------------------------------------------------------- 1 | Given a string s, return the number of palindromic substrings in it. 2 | 3 | A string is a palindrome when it reads the same backward as forward. 4 | 5 | A substring is a contiguous sequence of characters within the string. 6 | 7 | Example 1: 8 | Input: s = "abc" 9 | Output: 3 10 | Explanation: Three palindromic strings: "a", "b", "c". 11 | 12 | Example 2: 13 | Input: s = "aaa" 14 | Output: 6 15 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 16 | 17 | -------------------------------------------------------------------------------- /My_Learning/Day_17/LengthOfLastWord.py: -------------------------------------------------------------------------------- 1 | def length_of_last_word(s): 2 | # Split the string into words using spaces as separators 3 | words = s.split() 4 | 5 | # Check if there are words in the string 6 | if len(words) == 0: 7 | return 0 8 | 9 | # Return the length of the last word 10 | return len(words[-1]) 11 | 12 | 13 | user_input = input("Enter a string consisting of words and spaces: ") 14 | 15 | result = length_of_last_word(user_input) 16 | print("Output:", result) 17 | -------------------------------------------------------------------------------- /My_Learning/Day_51/HIndex.py: -------------------------------------------------------------------------------- 1 | def hIndex(citations): 2 | citations.sort(reverse=True) # Sort the citations array in descending order 3 | n = len(citations) 4 | h = 0 5 | for i in range(n): 6 | if citations[i] >= i + 1: 7 | h = i + 1 8 | else: 9 | break 10 | return h 11 | 12 | # Test cases 13 | citations1 = [3, 0, 6, 1, 5] 14 | citations2 = [1, 3, 1] 15 | 16 | print(hIndex(citations1)) # Output: 3 17 | print(hIndex(citations2)) # Output: 1 18 | -------------------------------------------------------------------------------- /My_Learning/Day_10/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. 2 | 3 | Example 1: 4 | 5 | Input: nums = [1,2,3,1], k = 3 6 | Output: true 7 | Example 2: 8 | 9 | Input: nums = [1,0,1,1], k = 1 10 | Output: true 11 | Example 3: 12 | 13 | Input: nums = [1,2,3,1,2,3], k = 2 14 | Output: false 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= nums.length <= 105 20 | -109 <= nums[i] <= 109 21 | 0 <= k <= 105 22 | -------------------------------------------------------------------------------- /My_Learning/Day_68/ques: -------------------------------------------------------------------------------- 1 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: nums = [1,2,3] 8 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 9 | Example 2: 10 | 11 | Input: nums = [0,1] 12 | Output: [[0,1],[1,0]] 13 | Example 3: 14 | 15 | Input: nums = [1] 16 | Output: [[1]] 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 6 22 | -10 <= nums[i] <= 10 23 | All the integers of nums are unique. 24 | -------------------------------------------------------------------------------- /My_Learning/Day_73/ques: -------------------------------------------------------------------------------- 1 | An array nums of length n is beautiful if: 2 | 3 | nums is a permutation of the integers in the range [1, n]. 4 | For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]. 5 | Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n. 6 | 7 | Example 1: 8 | Input: n = 4 9 | Output: [2,1,4,3] 10 | 11 | Example 2: 12 | Input: n = 5 13 | Output: [3,1,2,5,4] 14 | 15 | Constraints: 16 | 17 | 1 <= n <= 1000 18 | -------------------------------------------------------------------------------- /My_Learning/Day_7/Valid_Palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s): 2 | # Convert to lowercase and remove non-alphanumeric characters 3 | cleaned_str = ''.join(char.lower() for char in s if char.isalnum()) 4 | 5 | # Check if the cleaned string is equal to its reverse 6 | return cleaned_str == cleaned_str[::-1] 7 | 8 | # Take user input 9 | user_input = input("Enter a string: ") 10 | 11 | # Check if the input is a palindrome 12 | result = is_palindrome(user_input) 13 | 14 | # Display the result 15 | print("Output:", result) 16 | -------------------------------------------------------------------------------- /My_Learning/Day_39/peakElement.py: -------------------------------------------------------------------------------- 1 | def findPeakElement(nums): 2 | left, right = 0, len(nums) - 1 3 | 4 | while left < right: 5 | mid = left + (right - left) // 2 6 | if nums[mid] < nums[mid + 1]: 7 | left = mid + 1 8 | else: 9 | right = mid 10 | 11 | return left 12 | 13 | # Example usage: 14 | nums1 = [1, 2, 3, 1] 15 | nums2 = [1, 2, 1, 3, 5, 6, 4] 16 | print("Peak index in nums1:", findPeakElement(nums1)) # Output: 2 17 | print("Peak index in nums2:", findPeakElement(nums2)) # Output: 5 18 | -------------------------------------------------------------------------------- /My_Learning/Day_81/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. 2 | 3 | Example 1: 4 | Input: nums = [1,2,3,4,5,6,7], k = 3 5 | Output: [5,6,7,1,2,3,4] 6 | Explanation: 7 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 8 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 9 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 10 | 11 | Example 2: 12 | Input: nums = [-1,-100,3,99], k = 2 13 | Output: [3,99,-1,-100] 14 | Explanation: 15 | rotate 1 steps to the right: [99,-1,-100,3] 16 | rotate 2 steps to the right: [3,99,-1,-100] 17 | -------------------------------------------------------------------------------- /My_Learning/Day_11/ques: -------------------------------------------------------------------------------- 1 | def reverseString(s): 2 | left, right = 0, len(s) - 1 3 | 4 | while left < right: 5 | s[left], s[right] = s[right], s[left] 6 | left += 1 7 | right -= 1 8 | 9 | # Take user input for the array of characters 10 | try: 11 | input_string = input("Enter a string: ") 12 | char_array = list(input_string) 13 | 14 | # Reverse the string in-place 15 | reverseString(char_array) 16 | 17 | print("Reversed String:", char_array) 18 | except ValueError: 19 | print("Invalid input. Please enter a valid string.") 20 | -------------------------------------------------------------------------------- /My_Learning/Day_18/ques: -------------------------------------------------------------------------------- 1 | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. 2 | 3 | By listing and labeling all of the permutations in order, we get the following sequence for n = 3: 4 | 5 | "123" 6 | "132" 7 | "213" 8 | "231" 9 | "312" 10 | "321" 11 | Given n and k, return the kth permutation sequence. 12 | 13 | Example 1: 14 | 15 | Input: n = 3, k = 3 16 | Output: "213" 17 | Example 2: 18 | 19 | Input: n = 4, k = 9 20 | Output: "2314" 21 | Example 3: 22 | 23 | Input: n = 3, k = 1 24 | Output: "123" 25 | 26 | Constraints: 27 | 28 | 1 <= n <= 9 29 | 1 <= k <= n! 30 | -------------------------------------------------------------------------------- /My_Learning/Day_80/ques: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, flatten the tree into a "linked list": 2 | 3 | The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. 4 | The "linked list" should be in the same order as a pre-order traversal of the binary tree. 5 | 6 | 7 | Example 1: 8 | Input: root = [1,2,5,3,4,null,6] 9 | Output: [1,null,2,null,3,null,4,null,5,null,6] 10 | 11 | Example 2: 12 | Input: root = [] 13 | Output: [] 14 | 15 | Example 3: 16 | Input: root = [0] 17 | Output: [0] 18 | -------------------------------------------------------------------------------- /My_Learning/Day_50/LargestNumber.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def largestNumber(nums: List[int]) -> str: 4 | def compare(x, y): 5 | return int(y + x) - int(x + y) 6 | 7 | nums = [str(num) for num in nums] 8 | 9 | nums.sort(key=lambda x: (x[0], x), reverse=True) 10 | 11 | result = ''.join(nums) 12 | 13 | result = result.lstrip('0') 14 | 15 | return result or '0' 16 | 17 | # Test cases 18 | nums1 = [10, 2] 19 | nums2 = [3, 30, 34, 5, 9] 20 | 21 | print(largestNumber(nums1)) 22 | print(largestNumber(nums2)) 23 | -------------------------------------------------------------------------------- /My_Learning/Day_84/Add_Binary.py: -------------------------------------------------------------------------------- 1 | def addBinary(a, b): 2 | # Convert binary strings to integers 3 | int_a = int(a, 2) 4 | int_b = int(b, 2) 5 | 6 | # Add the integers 7 | sum_decimal = int_a + int_b 8 | 9 | # Convert the sum back to binary string 10 | sum_binary = bin(sum_decimal)[2:] 11 | 12 | return sum_binary 13 | 14 | # User input prompt 15 | a = input("Enter the first binary string: ") 16 | b = input("Enter the second binary string: ") 17 | 18 | # Call the function and print the result 19 | print("Sum of", a, "and", b, "is:", addBinary(a, b)) 20 | -------------------------------------------------------------------------------- /My_Learning/Day_64/ques: -------------------------------------------------------------------------------- 1 | A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). 2 | 3 | For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even. 4 | Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. 5 | 6 | A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. 7 | -------------------------------------------------------------------------------- /My_Learning/Day_18/PermutationSequence.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def getPermutation(n, k): 4 | nums = list(range(1, n + 1)) 5 | k -= 1 6 | ans = "" 7 | for i in range(n, 0, -1): 8 | index = k // math.factorial(i - 1) 9 | k %= math.factorial(i - 1) 10 | ans += str(nums[index]) 11 | nums.pop(index) 12 | return ans 13 | 14 | # Take user input for n and k 15 | n = int(input("Enter the value of n: ")) 16 | k = int(input("Enter the value of k: ")) 17 | 18 | # Calculate and print the result 19 | result = getPermutation(n, k) 20 | print("Output:", result) 21 | 22 | -------------------------------------------------------------------------------- /My_Learning/Day_22/ques: -------------------------------------------------------------------------------- 1 | Write a bash script to calculate the frequency of each word in a text file words.txt. 2 | 3 | For simplicity sake, you may assume: 4 | 5 | words.txt contains only lowercase characters and space ' ' characters. 6 | Each word must consist of lowercase characters only. 7 | Words are separated by one or more whitespace characters. 8 | Example: 9 | 10 | Assume that words.txt has the following content: 11 | 12 | the day is sunny the the 13 | the sunny is is 14 | Your script should output the following, sorted by descending frequency: 15 | 16 | the 4 17 | is 3 18 | sunny 2 19 | day 1 20 | -------------------------------------------------------------------------------- /My_Learning/Day_16/Pascals_triangle.py: -------------------------------------------------------------------------------- 1 | def generate_pascals_triangle(numRows): 2 | triangle = [] 3 | 4 | for i in range(numRows): 5 | row = [1] * (i + 1) 6 | 7 | for j in range(1, i): 8 | row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j] 9 | 10 | triangle.append(row) 11 | 12 | return triangle 13 | 14 | # Take user input for the number of rows 15 | numRows = int(input("Enter the number of rows for Pascal's triangle: ")) 16 | 17 | # Generate and print Pascal's triangle 18 | result = generate_pascals_triangle(numRows) 19 | print(result) 20 | -------------------------------------------------------------------------------- /My_Learning/Day_11/Reverse_String.py: -------------------------------------------------------------------------------- 1 | def reverseString(s): 2 | left, right = 0, len(s) - 1 3 | 4 | while left < right: 5 | s[left], s[right] = s[right], s[left] 6 | left += 1 7 | right -= 1 8 | 9 | # Take user input for the array of characters 10 | try: 11 | input_string = input("Enter a string: ") 12 | char_array = list(input_string) 13 | 14 | # Reverse the string in-place 15 | reverseString(char_array) 16 | 17 | print("Reversed String:", char_array) 18 | except ValueError: 19 | print("Invalid input. Please enter a valid string.") 20 | -------------------------------------------------------------------------------- /My_Learning/Day_63/ques: -------------------------------------------------------------------------------- 1 | You are given the head of a linked list. 2 | 3 | Remove every node which has a node with a greater value anywhere to the right side of it. 4 | 5 | Return the head of the modified linked list. 6 | 7 | Example 1: 8 | Input: head = [5,2,13,3,8] 9 | Output: [13,8] 10 | Explanation: The nodes that should be removed are 5, 2 and 3. 11 | - Node 13 is to the right of node 5. 12 | - Node 13 is to the right of node 2. 13 | - Node 8 is to the right of node 3. 14 | 15 | Example 2: 16 | Input: head = [1,1,1,1] 17 | Output: [1,1,1,1] 18 | Explanation: Every node has value 1, so no nodes are removed. 19 | -------------------------------------------------------------------------------- /My_Learning/Day_73/BeautifulArray.py: -------------------------------------------------------------------------------- 1 | def beautifulArray(n): 2 | if n == 1: 3 | return [1] 4 | 5 | odd_half = beautifulArray((n + 1) // 2) # Recursively construct beautiful array for odd numbers 6 | even_half = beautifulArray(n // 2) # Recursively construct beautiful array for even numbers 7 | 8 | # Merge the two halves to form the final beautiful array 9 | return [2 * x - 1 for x in odd_half] + [2 * x for x in even_half] 10 | 11 | # Example usage: 12 | print(beautifulArray(4)) # Output: [2, 1, 4, 3] 13 | print(beautifulArray(5)) # Output: [3, 1, 2, 5, 4] 14 | -------------------------------------------------------------------------------- /My_Learning/Day_5/Valid_Anagram.py: -------------------------------------------------------------------------------- 1 | def is_anagram(s, t): 2 | # Remove spaces and convert to lowercase for case-insensitive comparison 3 | s = s.replace(" ", "").lower() 4 | t = t.replace(" ", "").lower() 5 | 6 | # Check if the sorted characters of both strings are the same 7 | return sorted(s) == sorted(t) 8 | 9 | # Take user input for two strings 10 | s_input = input("Enter the first string: ") 11 | t_input = input("Enter the second string: ") 12 | 13 | # Check if the strings are anagrams 14 | result = is_anagram(s_input, t_input) 15 | 16 | # Display the result 17 | print(f"Result: {result}") -------------------------------------------------------------------------------- /My_Learning/Day_41/ques: -------------------------------------------------------------------------------- 1 | Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 2 | 3 | 0 <= a, b, c, d < n 4 | a, b, c, and d are distinct. 5 | nums[a] + nums[b] + nums[c] + nums[d] == target 6 | You may return the answer in any order. 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,0,-1,0,-2,2], target = 0 11 | Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] 12 | Example 2: 13 | 14 | Input: nums = [2,2,2,2,2], target = 8 15 | Output: [[2,2,2,2]] 16 | 17 | Constraints: 18 | 19 | 1 <= nums.length <= 200 20 | -109 <= nums[i] <= 109 21 | -109 <= target <= 109 22 | -------------------------------------------------------------------------------- /My_Learning/Day_74/Roam_2_integer.py: -------------------------------------------------------------------------------- 1 | def romanToInt(s: str) -> int: 2 | roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 3 | total = 0 4 | prev_value = 0 5 | 6 | for char in s: 7 | current_value = roman_dict[char] 8 | if current_value > prev_value: 9 | total += current_value - 2 * prev_value 10 | else: 11 | total += current_value 12 | prev_value = current_value 13 | 14 | return total 15 | 16 | # Take user input 17 | user_input = input("Enter a Roman numeral: ") 18 | print("Integer value:", romanToInt(user_input)) 19 | -------------------------------------------------------------------------------- /My_Learning/Day_46/ques: -------------------------------------------------------------------------------- 1 | Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 2 | 3 | 0 <= a, b, c, d < n 4 | a, b, c, and d are distinct. 5 | nums[a] + nums[b] + nums[c] + nums[d] == target 6 | You may return the answer in any order. 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,0,-1,0,-2,2], target = 0 11 | Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] 12 | Example 2: 13 | 14 | Input: nums = [2,2,2,2,2], target = 8 15 | Output: [[2,2,2,2]] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= nums.length <= 200 21 | -109 <= nums[i] <= 109 22 | -109 <= target <= 109 23 | -------------------------------------------------------------------------------- /My_Learning/Day_26/WordBreak.py: -------------------------------------------------------------------------------- 1 | def word_break(s, wordDict): 2 | n = len(s) 3 | dp = [False] * (n + 1) 4 | dp[0] = True 5 | 6 | for i in range(1, n + 1): 7 | for j in range(i): 8 | if dp[j] and s[j:i] in wordDict: 9 | dp[i] = True 10 | break 11 | 12 | return dp[n] 13 | 14 | # Taking user inputs 15 | s = input("Enter the string: ") 16 | wordDict = input("Enter the words in the dictionary separated by spaces: ").split() 17 | 18 | # Checking if s can be segmented using words from wordDict 19 | print(word_break(s, wordDict)) 20 | 21 | -------------------------------------------------------------------------------- /My_Learning/Day_56/ZigZag.py: -------------------------------------------------------------------------------- 1 | def convert(s, numRows): 2 | if numRows == 1 or numRows >= len(s): 3 | return s 4 | 5 | rows = [''] * numRows 6 | index, step = 0, 1 7 | 8 | for char in s: 9 | rows[index] += char 10 | if index == 0: 11 | step = 1 12 | elif index == numRows - 1: 13 | step = -1 14 | index += step 15 | 16 | return ''.join(rows) 17 | 18 | # Test cases 19 | print(convert("PAYPALISHIRING", 3)) # Output: "PAHNAPLSIIGYIR" 20 | print(convert("PAYPALISHIRING", 4)) # Output: "PINALSIGYAHRPI" 21 | print(convert("A", 1)) # Output: "A" 22 | -------------------------------------------------------------------------------- /My_Learning/Day_19/RegularExpressionMatching.py: -------------------------------------------------------------------------------- 1 | def isMatch(s, p): 2 | if not p: 3 | return not s 4 | 5 | first_match = bool(s) and p[0] in {s[0], '.'} 6 | 7 | if len(p) >= 2 and p[1] == '*': 8 | return (isMatch(s, p[2:]) or 9 | first_match and isMatch(s[1:], p)) 10 | else: 11 | return first_match and isMatch(s[1:], p[1:]) 12 | 13 | # Take user input for the input string s and pattern p 14 | s = input("Enter the input string s: ") 15 | p = input("Enter the pattern string p: ") 16 | 17 | # Check if the input string matches the pattern 18 | result = isMatch(s, p) 19 | print("Output:", result) 20 | 21 | -------------------------------------------------------------------------------- /My_Learning/Day_91/ques: -------------------------------------------------------------------------------- 1 | We can scramble a string s to get a string t using the following algorithm: 2 | 3 | If the length of the string is 1, stop. 4 | If the length of the string is > 1, do the following: 5 | Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y. 6 | Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x. 7 | Apply step 1 recursively on each of the two substrings x and y. 8 | Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false. 9 | -------------------------------------------------------------------------------- /My_Learning/Day_49/Zigzag_Conversion.py: -------------------------------------------------------------------------------- 1 | def convert(s: str, numRows: int) -> str: 2 | if numRows == 1 or numRows >= len(s): 3 | return s 4 | 5 | zigzag = [''] * numRows 6 | index, step = 0, 1 7 | 8 | for char in s: 9 | zigzag[index] += char 10 | if index == 0: 11 | step = 1 12 | elif index == numRows - 1: 13 | step = -1 14 | index += step 15 | 16 | return ''.join(zigzag) 17 | 18 | # Take user input 19 | s = input("Enter the string: ") 20 | numRows = int(input("Enter the number of rows: ")) 21 | 22 | # Call the convert function and print the result 23 | print(convert(s, numRows)) 24 | -------------------------------------------------------------------------------- /My_Learning/Day_6/Group_Anagram.py: -------------------------------------------------------------------------------- 1 | def group_anagrams(strs): 2 | anagrams = {} 3 | 4 | for word in strs: 5 | sorted_word = ''.join(sorted(word)) 6 | 7 | if sorted_word in anagrams: 8 | anagrams[sorted_word].append(word) 9 | else: 10 | anagrams[sorted_word] = [word] 11 | 12 | return list(anagrams.values()) 13 | 14 | # Taking user input 15 | user_input = input("Enter a list of strings separated by space: ") 16 | strs = user_input.split() 17 | 18 | # Grouping anagrams 19 | result = group_anagrams(strs) 20 | 21 | # Displaying the result 22 | print("Output:", result) 23 | -------------------------------------------------------------------------------- /My_Learning/Day_10/Contains_Duplicate_2.py: -------------------------------------------------------------------------------- 1 | def containsNearbyDuplicate(nums, k): 2 | num_indices = {} 3 | 4 | for i, num in enumerate(nums): 5 | if num in num_indices and abs(i - num_indices[num]) <= k: 6 | return True 7 | num_indices[num] = i 8 | 9 | return False 10 | 11 | # Take user input for nums and k 12 | try: 13 | nums = list(map(int, input("Enter array nums separated by space: ").split())) 14 | k = int(input("Enter value for k: ")) 15 | result = containsNearbyDuplicate(nums, k) 16 | print(f"Result: {result}") 17 | except ValueError: 18 | print("Invalid input. Please enter valid values.") 19 | -------------------------------------------------------------------------------- /My_Learning/Day_21/ScrambleString.py: -------------------------------------------------------------------------------- 1 | def isScramble(s1, s2): 2 | if s1 == s2: 3 | return True 4 | if sorted(s1) != sorted(s2): 5 | return False 6 | n = len(s1) 7 | for i in range(1, n): 8 | if (isScramble(s1[:i], s2[:i]) and isScramble(s1[i:], s2[i:])) or \ 9 | (isScramble(s1[:i], s2[-i:]) and isScramble(s1[i:], s2[:-i])): 10 | return True 11 | return False 12 | 13 | # Take user input for the strings s1 and s2 14 | s1 = input("Enter the first string s1: ") 15 | s2 = input("Enter the second string s2: ") 16 | 17 | # Check if s2 is a scrambled string of s1 18 | result = isScramble(s1, s2) 19 | print("Output:",result) -------------------------------------------------------------------------------- /My_Learning/Day_3/two_sum.py: -------------------------------------------------------------------------------- 1 | def twosum(nums, target): 2 | length = len(nums) 3 | for i in range(length): 4 | for j in range(i + 1, length): 5 | if nums[i] + nums[j] == target: 6 | return [i, j] 7 | 8 | # Take user input for nums 9 | nums_input = input("Enter a list of numbers separated by spaces: ") 10 | nums = [int(num) for num in nums_input.split()] 11 | 12 | # Take user input for target 13 | target = int(input("Enter the target sum: ")) 14 | 15 | result = twosum(nums, target) 16 | if result: 17 | print(f"Indices of the two numbers that add up to {target}: {result}") 18 | else: 19 | print("No solution found.") 20 | -------------------------------------------------------------------------------- /My_Learning/Day_77/ques: -------------------------------------------------------------------------------- 1 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 2 | 3 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 4 | 5 | You may assume that you have an infinite number of each kind of coin. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: coins = [1,2,5], amount = 11 12 | Output: 3 13 | Explanation: 11 = 5 + 5 + 1 14 | Example 2: 15 | 16 | Input: coins = [2], amount = 3 17 | Output: -1 18 | Example 3: 19 | 20 | Input: coins = [1], amount = 0 21 | Output: 0 22 | 23 | -------------------------------------------------------------------------------- /My_Learning/Day_79/BinaryTree.py: -------------------------------------------------------------------------------- 1 | def numTrees(n): 2 | # Initialize dp array with 0s (dp[i] will store the number of unique BSTs with i nodes) 3 | dp = [0] * (n + 1) 4 | 5 | # Base cases 6 | dp[0] = 1 # Empty tree (1 way to represent an empty tree) 7 | dp[1] = 1 # Single node tree (1 way to represent a tree with a single node) 8 | 9 | # Fill dp array for each number of nodes from 2 to n 10 | for i in range(2, n + 1): 11 | for j in range(1, i + 1): 12 | dp[i] += dp[j - 1] * dp[i - j] 13 | 14 | return dp[n] 15 | 16 | # Test cases 17 | print(numTrees(3)) # Output: 5 18 | print(numTrees(1)) # Output: 1 19 | -------------------------------------------------------------------------------- /My_Learning/Day_95/ques: -------------------------------------------------------------------------------- 1 | You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. 2 | 3 | Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue). 4 | 5 | Example : 6 | 7 | Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] 8 | Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 9 | -------------------------------------------------------------------------------- /My_Learning/Day_4/Contains_Duplicate.py: -------------------------------------------------------------------------------- 1 | import array 2 | 3 | def containsDuplicate(nums): 4 | nums = sorted(nums) # Sort the array in ascending order 5 | 6 | # Check for duplicates 7 | for i in range(len(nums) - 1): 8 | if nums[i] == nums[i + 1]: 9 | return True 10 | 11 | # No duplicates found 12 | return False 13 | 14 | # Take user input for the integer array 15 | user_input = input("Enter integers separated by spaces: ") 16 | nums_array = array.array('i', map(int, user_input.split())) 17 | 18 | # Check for duplicates and print the result 19 | result = containsDuplicate(nums_array) 20 | print("Output:", result) 21 | 22 | 23 | -------------------------------------------------------------------------------- /My_Learning/Day_44/PlusOne.py: -------------------------------------------------------------------------------- 1 | def plusOne(digits): 2 | n = len(digits) 3 | carry = 1 4 | for i in range(n - 1, -1, -1): 5 | if digits[i] + carry == 10: 6 | digits[i] = 0 7 | carry = 1 8 | else: 9 | digits[i] += carry 10 | carry = 0 11 | break 12 | if carry == 1: 13 | digits.insert(0, 1) 14 | return digits 15 | 16 | # Test the function 17 | digits1 = [1, 2, 3] 18 | print(plusOne(digits1)) # Output: [1, 2, 4] 19 | 20 | digits2 = [4, 3, 2, 1] 21 | print(plusOne(digits2)) # Output: [4, 3, 2, 2] 22 | 23 | digits3 = [9] 24 | print(plusOne(digits3)) # Output: [1, 0] 25 | -------------------------------------------------------------------------------- /My_Learning/Day_45/ques: -------------------------------------------------------------------------------- 1 | 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. 2 | 3 | Return the sum of the three integers. 4 | 5 | You may assume that each input would have exactly one solution. 6 | Example 1: 7 | 8 | Input: nums = [-1,2,1,-4], target = 1 9 | Output: 2 10 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 11 | Example 2: 12 | 13 | Input: nums = [0,0,0], target = 1 14 | Output: 0 15 | Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). 16 | Constraints: 17 | 18 | 3 <= nums.length <= 500 19 | -1000 <= nums[i] <= 1000 20 | -104 <= target <= 104 21 | -------------------------------------------------------------------------------- /My_Learning/Day_12/Moves_Zero.py: -------------------------------------------------------------------------------- 1 | def moveZeroes(nums): 2 | non_zero_index = 0 3 | 4 | # Move non-zero elements to the beginning 5 | for i in range(len(nums)): 6 | if nums[i] != 0: 7 | nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index] 8 | non_zero_index += 1 9 | 10 | # Take user input for the array of integers 11 | try: 12 | nums = list(map(int, input("Enter an array of integers separated by space: ").split())) 13 | 14 | # Move 0's to the end in-place 15 | moveZeroes(nums) 16 | 17 | print("Result:", nums) 18 | except ValueError: 19 | print("Invalid input. Please enter a valid array of integers.") 20 | -------------------------------------------------------------------------------- /My_Learning/Day_42/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. 2 | 3 | Example 1: 4 | 5 | Input: nums = [1,2,3,4,5,6,7], k = 3 6 | Output: [5,6,7,1,2,3,4] 7 | Explanation: 8 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 9 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 10 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 11 | Example 2: 12 | 13 | Input: nums = [-1,-100,3,99], k = 2 14 | Output: [3,99,-1,-100] 15 | Explanation: 16 | rotate 1 steps to the right: [99,-1,-100,3] 17 | rotate 2 steps to the right: [3,99,-1,-100] 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 105 22 | -231 <= nums[i] <= 231 - 1 23 | 0 <= k <= 105 24 | 25 | -------------------------------------------------------------------------------- /My_Learning/Day_65/ques: -------------------------------------------------------------------------------- 1 | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 2 | 3 | You must write an algorithm with O(log n) runtime complexity. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [1,3,5,6], target = 5 10 | Output: 2 11 | Example 2: 12 | 13 | Input: nums = [1,3,5,6], target = 2 14 | Output: 1 15 | Example 3: 16 | 17 | Input: nums = [1,3,5,6], target = 7 18 | Output: 4 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= nums.length <= 104 24 | -104 <= nums[i] <= 104 25 | nums contains distinct values sorted in ascending order. 26 | -104 <= target <= 104 27 | -------------------------------------------------------------------------------- /My_Learning/Day_30/flowerbed.py: -------------------------------------------------------------------------------- 1 | def canPlaceFlowers(flowerbed, n): 2 | count = 0 3 | i = 0 4 | while i < len(flowerbed): 5 | if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0): 6 | flowerbed[i] = 1 7 | count += 1 8 | i += 1 9 | return count >= n 10 | 11 | # Take user input for flowerbed array 12 | flowerbed = list(map(int, input("Enter the flowerbed array (separated by spaces): ").split())) 13 | 14 | # Take user input for n 15 | n = int(input("Enter the value of n: ")) 16 | 17 | # Call the function and print the result 18 | print("Output:", canPlaceFlowers(flowerbed, n)) 19 | -------------------------------------------------------------------------------- /My_Learning/Day_60/ques: -------------------------------------------------------------------------------- 1 | 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. 2 | 3 | Return the sum of the three integers. 4 | 5 | You may assume that each input would have exactly one solution. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [-1,2,1,-4], target = 1 12 | Output: 2 13 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 14 | Example 2: 15 | 16 | Input: nums = [0,0,0], target = 1 17 | Output: 0 18 | Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). 19 | 20 | 21 | Constraints: 22 | 23 | 3 <= nums.length <= 500 24 | -1000 <= nums[i] <= 1000 25 | -104 <= target <= 104 26 | -------------------------------------------------------------------------------- /My_Learning/Day_42/RotateArray.py: -------------------------------------------------------------------------------- 1 | def rotate(nums, k): 2 | n = len(nums) 3 | k %= n 4 | 5 | def reverse(arr, start, end): 6 | while start < end: 7 | arr[start], arr[end] = arr[end], arr[start] 8 | start += 1 9 | end -= 1 10 | 11 | reverse(nums, 0, n - 1) 12 | reverse(nums, 0, k - 1) 13 | reverse(nums, k, n - 1) 14 | 15 | # Example usage: 16 | nums1 = [1, 2, 3, 4, 5, 6, 7] 17 | k1 = 3 18 | nums2 = [-1, -100, 3, 99] 19 | k2 = 2 20 | 21 | rotate(nums1, k1) 22 | rotate(nums2, k2) 23 | 24 | print("Output for nums1:", nums1) # Output: [5, 6, 7, 1, 2, 3, 4] 25 | print("Output for nums2:", nums2) # Output: [3, 99, -1, -100] 26 | -------------------------------------------------------------------------------- /My_Learning/Day_38/Decode_string.py: -------------------------------------------------------------------------------- 1 | def decodeString(s): 2 | stack = [] 3 | curr_str = "" 4 | k = 0 5 | 6 | for char in s: 7 | if char.isdigit(): 8 | k = k * 10 + int(char) 9 | elif char.isalpha(): 10 | curr_str += char 11 | elif char == '[': 12 | stack.append((curr_str, k)) 13 | curr_str = "" 14 | k = 0 15 | elif char == ']': 16 | prev_str, prev_k = stack.pop() 17 | curr_str = prev_str + curr_str * prev_k 18 | 19 | return curr_str 20 | 21 | # Take user input 22 | s = input("Enter the encoded string: ") 23 | decoded_string = decodeString(s) 24 | print("Decoded string:", decoded_string) 25 | -------------------------------------------------------------------------------- /My_Learning/Day_40/ques: -------------------------------------------------------------------------------- 1 | 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. 2 | 3 | Each number in candidates may only be used once in the combination. 4 | 5 | Note: The solution set must not contain duplicate combinations. 6 | 7 | Example 1: 8 | 9 | Input: candidates = [10,1,2,7,6,1,5], target = 8 10 | Output: 11 | [ 12 | [1,1,6], 13 | [1,2,5], 14 | [1,7], 15 | [2,6] 16 | ] 17 | Example 2: 18 | 19 | Input: candidates = [2,5,2,1,2], target = 5 20 | Output: 21 | [ 22 | [1,2,2], 23 | [5] 24 | ] 25 | 26 | Constraints: 27 | 28 | 1 <= candidates.length <= 100 29 | 1 <= candidates[i] <= 50 30 | 1 <= target <= 30 31 | -------------------------------------------------------------------------------- /My_Learning/Day_28/ques: -------------------------------------------------------------------------------- 1 | Given two strings s and t, determine if they are isomorphic. 2 | 3 | Two strings s and t are isomorphic if the characters in s can be replaced to get t. 4 | 5 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. 6 | 7 | Example 1: 8 | 9 | Input: s = "egg", t = "add" 10 | Output: true 11 | Example 2: 12 | 13 | Input: s = "foo", t = "bar" 14 | Output: false 15 | Example 3: 16 | 17 | Input: s = "paper", t = "title" 18 | Output: true 19 | 20 | Constraints: 21 | 22 | 1 <= s.length <= 5 * 104 23 | t.length == s.length 24 | s and t consist of any valid ascii character. 25 | -------------------------------------------------------------------------------- /My_Learning/Day_17/ques: -------------------------------------------------------------------------------- 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 substring consisting of non-space characters only. 4 | Example 1: 5 | 6 | Input: s = "Hello World" 7 | Output: 5 8 | Explanation: The last word is "World" with length 5. 9 | Example 2: 10 | 11 | Input: s = " fly me to the moon " 12 | Output: 4 13 | Explanation: The last word is "moon" with length 4. 14 | Example 3: 15 | 16 | Input: s = "luffy is still joyboy" 17 | Output: 6 18 | Explanation: The last word is "joyboy" with length 6. 19 | 20 | Constraints: 21 | 22 | 1 <= s.length <= 104 23 | s consists of only English letters and spaces ' '. 24 | There will be at least one word in s 25 | -------------------------------------------------------------------------------- /My_Learning/Day_97/Combinations.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def combine(self, n: int, k: int) -> List[List[int]]: 4 | def backtrack(start, k, current): 5 | if k == 0: 6 | result.append(current[:]) 7 | return 8 | for i in range(start, n + 1): 9 | current.append(i) 10 | backtrack(i + 1, k - 1, current) 11 | current.pop() 12 | 13 | result = [] 14 | backtrack(1, k, []) 15 | return result 16 | 17 | # Example usage 18 | sol = Solution() 19 | print(sol.combine(4, 2)) # Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 20 | print(sol.combine(1, 1)) # Output: [[1]] 21 | -------------------------------------------------------------------------------- /My_Learning/Day_9/Best_time_to_Sell&Buy_Stocks.py: -------------------------------------------------------------------------------- 1 | def maxProfit(prices): 2 | n = len(prices) 3 | if n <= 1: 4 | return 0 5 | 6 | max_profit = 0 7 | min_price = prices[0] 8 | 9 | for i in range(1, n): 10 | current_price = prices[i] 11 | max_profit = max(max_profit, current_price - min_price) 12 | min_price = min(min_price, current_price) 13 | 14 | return max_profit 15 | 16 | # Take user input for stock prices 17 | try: 18 | prices = list(map(int, input("Enter stock prices separated by space: ").split())) 19 | result = maxProfit(prices) 20 | print(f"Maximum profit: {result}") 21 | except ValueError: 22 | print("Invalid input. Please enter valid stock prices.") 23 | -------------------------------------------------------------------------------- /My_Learning/Day_62/ques: -------------------------------------------------------------------------------- 1 | 2 | Code 3 | Testcase 4 | Test Result 5 | Test Result 6 | 43. Multiply Strings 7 | Medium 8 | Topics 9 | Companies 10 | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. 11 | 12 | Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: num1 = "2", num2 = "3" 19 | Output: "6" 20 | Example 2: 21 | 22 | Input: num1 = "123", num2 = "456" 23 | Output: "56088" 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= num1.length, num2.length <= 200 29 | num1 and num2 consist of digits only. 30 | Both num1 and num2 do not contain any leading zero, except the number 0 itself. 31 | -------------------------------------------------------------------------------- /My_Learning/Day_65/Search_inserted_postion.py: -------------------------------------------------------------------------------- 1 | def search_insert_position(nums, target): 2 | left, right = 0, len(nums) - 1 3 | 4 | while left <= right: 5 | mid = left + (right - left) // 2 6 | if nums[mid] == target: 7 | return mid 8 | elif nums[mid] < target: 9 | left = mid + 1 10 | else: 11 | right = mid - 1 12 | 13 | return left 14 | 15 | # Example usage: 16 | nums1 = [1, 3, 5, 6] 17 | target1 = 5 18 | print(search_insert_position(nums1, target1)) # Output: 2 19 | 20 | nums2 = [1, 3, 5, 6] 21 | target2 = 2 22 | print(search_insert_position(nums2, target2)) # Output: 1 23 | 24 | nums3 = [1, 3, 5, 6] 25 | target3 = 7 26 | print(search_insert_position(nums3, target3)) # Output: 4 27 | -------------------------------------------------------------------------------- /My_Learning/Day_30/ques: -------------------------------------------------------------------------------- 1 | You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. 2 | 3 | Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: flowerbed = [1,0,0,0,1], n = 1 10 | Output: true 11 | Example 2: 12 | 13 | Input: flowerbed = [1,0,0,0,1], n = 2 14 | Output: false 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= flowerbed.length <= 2 * 104 20 | flowerbed[i] is 0 or 1. 21 | There are no two adjacent flowers in flowerbed. 22 | 0 <= n <= flowerbed.length 23 | -------------------------------------------------------------------------------- /My_Learning/Day_55/AssignCookies.py: -------------------------------------------------------------------------------- 1 | def findContentChildren(g, s): 2 | g.sort() # Sort the greed factors 3 | s.sort() # Sort the sizes of the cookies 4 | 5 | content_children = 0 6 | i = 0 # Pointer for greed factors 7 | j = 0 # Pointer for sizes of cookies 8 | 9 | while i < len(g) and j < len(s): 10 | if s[j] >= g[i]: # If the cookie size is greater than or equal to the child's greed factor 11 | content_children += 1 12 | i += 1 # Move to the next child 13 | j += 1 # Move to the next cookie 14 | 15 | return content_children 16 | 17 | # Test cases 18 | print(findContentChildren([1,2,3], [1,1])) # Output: 1 19 | print(findContentChildren([1,2], [1,2,3])) # Output: 2 20 | -------------------------------------------------------------------------------- /My_Learning/Day_33/PosionDuration.py: -------------------------------------------------------------------------------- 1 | def findPoisonedDuration(timeSeries, duration): 2 | if not timeSeries: 3 | return 0 4 | 5 | total_duration = 0 6 | for i in range(len(timeSeries) - 1): 7 | total_duration += min(timeSeries[i + 1] - timeSeries[i], duration) 8 | 9 | # Add the duration of the last attack 10 | total_duration += duration 11 | 12 | return total_duration 13 | 14 | # Take user input for timeSeries array 15 | timeSeries = list(map(int, input("Enter the time series array (separated by spaces): ").split())) 16 | 17 | # Take user input for duration 18 | duration = int(input("Enter the value of duration: ")) 19 | 20 | # Call the function and print the result 21 | print("Output:", findPoisonedDuration(timeSeries, duration)) 22 | -------------------------------------------------------------------------------- /My_Learning/Day_75/ques: -------------------------------------------------------------------------------- 1 | You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. 2 | 3 | Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. 4 | 5 | Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. 6 | -------------------------------------------------------------------------------- /My_Learning/Day_83/MaxSubArray.py: -------------------------------------------------------------------------------- 1 | def maxSubArray(nums): 2 | # Initialize variables to keep track of maximum sum found so far and current subarray sum 3 | max_sum = float('-inf') 4 | current_sum = 0 5 | 6 | # Iterate through each element in the array 7 | for num in nums: 8 | # Decide whether to start a new subarray with 'num' or continue the current subarray 9 | current_sum = max(num, current_sum + num) 10 | # Update the maximum sum found so far 11 | max_sum = max(max_sum, current_sum) 12 | 13 | return max_sum 14 | 15 | # Test cases 16 | print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) # Output: 6 17 | print(maxSubArray([1])) # Output: 1 18 | print(maxSubArray([5,4,-1,7,8])) # Output: 23 19 | -------------------------------------------------------------------------------- /My_Learning/Day_24/ques: -------------------------------------------------------------------------------- 1 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. 2 | 3 | Merge all the linked-lists into one sorted linked-list and return it. 4 | Example 1: 5 | 6 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 7 | Output: [1,1,2,3,4,4,5,6] 8 | Explanation: The linked-lists are: 9 | [ 10 | 1->4->5, 11 | 1->3->4, 12 | 2->6 13 | ] 14 | merging them into one sorted list: 15 | 1->1->2->3->4->4->5->6 16 | Example 2: 17 | 18 | Input: lists = [] 19 | Output: [] 20 | Example 3: 21 | 22 | Input: lists = [[]] 23 | Output: [] 24 | 25 | Constraints: 26 | 27 | k == lists.length 28 | 0 <= k <= 104 29 | 0 <= lists[i].length <= 500 30 | -104 <= lists[i][j] <= 104 31 | lists[i] is sorted in ascending order. 32 | The sum of lists[i].length will not exceed 104. 33 | -------------------------------------------------------------------------------- /My_Learning/Day_95/Queue.py: -------------------------------------------------------------------------------- 1 | def reconstructQueue(people): 2 | # Sort people array based on height (hi) descending and ki ascending 3 | people.sort(key=lambda x: (-x[0], x[1])) 4 | 5 | # Initialize the result list 6 | result = [] 7 | 8 | # Insert each person into the result list at the specified index (ki) 9 | for person in people: 10 | result.insert(person[1], person) 11 | 12 | return result 13 | 14 | # Test the reconstructQueue function with example inputs 15 | people1 = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] 16 | print(reconstructQueue(people1)) # Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 17 | 18 | people2 = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] 19 | print(reconstructQueue(people2)) # Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] 20 | -------------------------------------------------------------------------------- /My_Learning/Day_96/ques: -------------------------------------------------------------------------------- 1 | Design a HashMap without using any built-in hash table libraries. 2 | 3 | Implement the MyHashMap class: 4 | 5 | MyHashMap() initializes the object with an empty map. 6 | void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. 7 | int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. 8 | void remove(key) removes the key and its corresponding value if the map contains the mapping for the key. 9 | 10 | Example : 11 | 12 | Input 13 | ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] 14 | [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] 15 | Output 16 | [null, null, null, 1, -1, null, 1, null, -1] 17 | -------------------------------------------------------------------------------- /My_Learning/Day_2/guessing_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | print("Welcome to the guessing Game") 4 | 5 | lower_limit = 1 6 | upper_limit = 100 7 | secret_number = random.randint(lower_limit, upper_limit) 8 | 9 | for attempt in range(1, 6): # Allow up to 5 attempts 10 | print(f"Attempt {attempt}") 11 | 12 | guess = int(input("Enter your guess: ")) 13 | 14 | if guess == secret_number: 15 | print(f"Congratulations! You guessed the correct number {secret_number} in {attempt} attempts.") 16 | break 17 | elif guess < secret_number: 18 | print("Too low! Try again.") 19 | else: 20 | print("Too high! Try again.") 21 | else: 22 | print(f"Sorry, you've reached the maximum number of attempts. The correct number was {secret_number}.") 23 | 24 | -------------------------------------------------------------------------------- /My_Learning/Day_55/ques: -------------------------------------------------------------------------------- 1 | Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. 2 | 3 | Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. 4 | 5 | Example: 6 | 7 | Input: g = [1,2,3], s = [1,1] 8 | Output: 1 9 | Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 10 | And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. 11 | You need to output 1. 12 | -------------------------------------------------------------------------------- /My_Learning/Day_62/Multiple_Strings.py: -------------------------------------------------------------------------------- 1 | def multiply(num1: str, num2: str) -> str: 2 | if num1 == "0" or num2 == "0": 3 | return "0" 4 | 5 | m, n = len(num1), len(num2) 6 | result = [0] * (m + n) 7 | 8 | for i in range(m - 1, -1, -1): 9 | for j in range(n - 1, -1, -1): 10 | mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0')) 11 | total = mul + result[i + j + 1] 12 | result[i + j] += total // 10 13 | result[i + j + 1] = total % 10 14 | 15 | start = 0 16 | while start < len(result) and result[start] == 0: 17 | start += 1 18 | 19 | return ''.join(map(str, result[start:])) 20 | 21 | 22 | # Test cases 23 | num1 = input("Enter num1: ") 24 | num2 = input("Enter num2: ") 25 | print("Output:", multiply(num1, num2)) 26 | -------------------------------------------------------------------------------- /My_Learning/Day_93/Palindrome.py: -------------------------------------------------------------------------------- 1 | def countSubstrings(s): 2 | n = len(s) 3 | dp = [[False] * n for _ in range(n)] 4 | count = 0 5 | 6 | # Single character substrings are palindromes 7 | for i in range(n): 8 | dp[i][i] = True 9 | count += 1 10 | 11 | # Check for substrings of length 2 or greater 12 | for length in range(2, n + 1): # length of substring 13 | for i in range(n - length + 1): 14 | j = i + length - 1 15 | if s[i] == s[j]: 16 | if length == 2 or dp[i+1][j-1]: 17 | dp[i][j] = True 18 | count += 1 19 | 20 | return count 21 | 22 | # Test cases 23 | print(countSubstrings("abc")) # Output: 3 24 | print(countSubstrings("aaa")) # Output: 6 25 | -------------------------------------------------------------------------------- /My_Learning/Day_52/TaskScheduler.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | def leastInterval(tasks, n): 4 | 5 | task_count = Counter(tasks) 6 | 7 | max_frequency = max(task_count.values()) 8 | 9 | max_frequency_tasks = sum(1 for count in task_count.values() if count == max_frequency) 10 | 11 | minimum_intervals = (max_frequency - 1) * (n + 1) + max_frequency_tasks 12 | 13 | return max(minimum_intervals, len(tasks)) 14 | 15 | # Test cases 16 | tasks1 = ["A","A","A","B","B","B"] 17 | n1 = 2 18 | tasks2 = ["A","C","A","B","D","B"] 19 | n2 = 1 20 | tasks3 = ["A","A","A","B","B","B"] 21 | n3 = 3 22 | 23 | print(leastInterval(tasks1, n1)) # Output: 8 24 | print(leastInterval(tasks2, n2)) # Output: 6 25 | print(leastInterval(tasks3, n3)) # Output: 10 26 | -------------------------------------------------------------------------------- /My_Learning/Day_57/ques: -------------------------------------------------------------------------------- 1 | Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. 2 | 3 | Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. 4 | 5 | After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. 6 | -------------------------------------------------------------------------------- /My_Learning/Day_14/Merge_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | def merge(nums1, m, nums2, n): 2 | # Start from the end of nums1 and nums2 3 | i, j, k = m - 1, n - 1, m + n - 1 4 | 5 | # Merge elements from nums1 and nums2 in descending order 6 | while i >= 0 and j >= 0: 7 | if nums1[i] > nums2[j]: 8 | nums1[k] = nums1[i] 9 | i -= 1 10 | else: 11 | nums1[k] = nums2[j] 12 | j -= 1 13 | k -= 1 14 | 15 | # If there are remaining elements in nums2, copy them to nums1 16 | while j >= 0: 17 | nums1[k] = nums2[j] 18 | j -= 1 19 | k -= 1 20 | 21 | # Example usage: 22 | nums1 = [1, 2, 3, 0, 0, 0] 23 | m = 3 24 | nums2 = [2, 5, 6] 25 | n = 3 26 | 27 | merge(nums1, m, nums2, n) 28 | print(nums1) # Output: [1, 2, 2, 3, 5, 6] 29 | -------------------------------------------------------------------------------- /My_Learning/Day_47/ques: -------------------------------------------------------------------------------- 1 | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. 2 | 3 | Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). 4 | 5 | Return intervals after the insertion. 6 | 7 | Example 1: 8 | 9 | Input: intervals = [[1,3],[6,9]], newInterval = [2,5] 10 | Output: [[1,5],[6,9]] 11 | 12 | Example 2: 13 | 14 | Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 15 | Output: [[1,2],[3,10],[12,16]] 16 | -------------------------------------------------------------------------------- /My_Learning/Day_69/Jump_Game.py: -------------------------------------------------------------------------------- 1 | def min_jumps(nums): 2 | n = len(nums) 3 | if n == 1: 4 | return 0 5 | 6 | jumps = 1 # Number of jumps needed 7 | current_max_reach = nums[0] # The farthest index reachable with the current jump 8 | next_max_reach = nums[0] # The farthest index reachable with the next jump 9 | 10 | for i in range(1, n): 11 | if i > current_max_reach: 12 | jumps += 1 13 | current_max_reach = next_max_reach 14 | 15 | next_max_reach = max(next_max_reach, i + nums[i]) 16 | 17 | return jumps 18 | 19 | # Taking input from the user 20 | nums = list(map(int, input("Enter the array of integers separated by space: ").split())) 21 | 22 | # Calculating and printing the minimum number of jumps 23 | print("Minimum number of jumps required:", min_jumps(nums)) 24 | -------------------------------------------------------------------------------- /My_Learning/Day_82/ques: -------------------------------------------------------------------------------- 1 | A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. 2 | 3 | For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. 4 | Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. 5 | 6 | Example 1: 7 | Input: s = "25525511135" 8 | Output: ["255.255.11.135","255.255.111.35"] 9 | 10 | Example 2: 11 | Input: s = "0000" 12 | Output: ["0.0.0.0"] 13 | 14 | Example 3: 15 | Input: s = "101023" 16 | Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"] 17 | -------------------------------------------------------------------------------- /My_Learning/Day_22/wordFrequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | # Function to calculate word frequency 4 | def word_frequency(text): 5 | words = text.split() 6 | word_counts = Counter(words) 7 | sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True) 8 | return sorted_word_counts 9 | 10 | # Take user input for the file name 11 | file_name = input("Enter the file name: ") 12 | 13 | try: 14 | # Read the content of the file 15 | with open(file_name, 'r') as file: 16 | file_content = file.read() 17 | # Calculate word frequency 18 | result = word_frequency(file_content) 19 | # Print the result 20 | for word, frequency in result: 21 | print(word, frequency) 22 | except FileNotFoundError: 23 | print("File not found.") 24 | 25 | -------------------------------------------------------------------------------- /My_Learning/Day_76/ques: -------------------------------------------------------------------------------- 1 | Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. 2 | 3 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 4 | 5 | You must find a solution with a memory complexity better than O(n2). 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 12 | Output: 13 13 | Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13 14 | Example 2: 15 | 16 | Input: matrix = [[-5]], k = 1 17 | Output: -5 18 | 19 | 20 | Constraints: 21 | 22 | n == matrix.length == matrix[i].length 23 | 1 <= n <= 300 24 | -109 <= matrix[i][j] <= 109 25 | All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order. 26 | 1 <= k <= n2 27 | -------------------------------------------------------------------------------- /My_Learning/Day_86/ques: -------------------------------------------------------------------------------- 1 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 2 | 3 | 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. 4 | 5 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 6 | 7 | Example 1: 8 | Input: prices = [7,1,5,3,6,4] 9 | Output: 5 10 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 11 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 12 | 13 | Example 2: 14 | Input: prices = [7,6,4,3,1] 15 | Output: 0 16 | Explanation: In this case, no transactions are done and the max profit = 0. 17 | 18 | Constraints: 19 | 20 | 1 <= prices.length <= 105 21 | 0 <= prices[i] <= 104 22 | -------------------------------------------------------------------------------- /My_Learning/Day_25/Candy.py: -------------------------------------------------------------------------------- 1 | def candy(ratings): 2 | n = len(ratings) 3 | candies = [1] * n 4 | 5 | # Traverse from left to right 6 | for i in range(1, n): 7 | if ratings[i] > ratings[i - 1]: 8 | candies[i] = candies[i - 1] + 1 9 | 10 | # Traverse from right to left 11 | for i in range(n - 2, -1, -1): 12 | if ratings[i] > ratings[i + 1]: 13 | candies[i] = max(candies[i], candies[i + 1] + 1) 14 | 15 | # Calculate the total number of candies needed 16 | total_candies = sum(candies) 17 | return total_candies 18 | 19 | # Take user input for the ratings of the children 20 | ratings = list(map(int, input("Enter the ratings of the children separated by space: ").split())) 21 | 22 | # Calculate the minimum number of candies needed 23 | result = candy(ratings) 24 | print("Output:", result) 25 | -------------------------------------------------------------------------------- /My_Learning/Day_29/LRUCache.py: -------------------------------------------------------------------------------- 1 | def candy(ratings): 2 | n = len(ratings) 3 | candies = [1] * n 4 | 5 | # Traverse from left to right 6 | for i in range(1, n): 7 | if ratings[i] > ratings[i - 1]: 8 | candies[i] = candies[i - 1] + 1 9 | 10 | # Traverse from right to left 11 | for i in range(n - 2, -1, -1): 12 | if ratings[i] > ratings[i + 1]: 13 | candies[i] = max(candies[i], candies[i + 1] + 1) 14 | 15 | # Calculate the total number of candies needed 16 | total_candies = sum(candies) 17 | return total_candies 18 | 19 | # Take user input for the ratings of the children 20 | ratings = list(map(int, input("Enter the ratings of the children separated by space: ").split())) 21 | 22 | # Calculate the minimum number of candies needed 23 | result = candy(ratings) 24 | print("Output:", result) 25 | -------------------------------------------------------------------------------- /My_Learning/Day_35/ques: -------------------------------------------------------------------------------- 1 | You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. 2 | 3 | Return the length of the longest substring containing the same letter you can get after performing the above operations. 4 | 5 | Example 1: 6 | 7 | Input: s = "ABAB", k = 2 8 | Output: 4 9 | Explanation: Replace the two 'A's with two 'B's or vice versa. 10 | Example 2: 11 | 12 | Input: s = "AABABBA", k = 1 13 | Output: 4 14 | Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". 15 | The substring "BBBB" has the longest repeating letters, which is 4. 16 | There may exists other ways to achieve this answer too. 17 | 18 | Constraints: 19 | 20 | 1 <= s.length <= 105 21 | s consists of only uppercase English letters. 22 | 0 <= k <= s.length 23 | -------------------------------------------------------------------------------- /My_Learning/Day_59/combinationSum.py: -------------------------------------------------------------------------------- 1 | def combinationSum(candidates, target): 2 | def backtrack(start, target, path): 3 | if target == 0: 4 | result.append(path) 5 | return 6 | if target < 0: 7 | return 8 | for i in range(start, len(candidates)): 9 | backtrack(i, target - candidates[i], path + [candidates[i]]) 10 | 11 | result = [] 12 | candidates.sort() 13 | backtrack(0, target, []) 14 | return result 15 | 16 | # Example usage: 17 | candidates1 = [2, 3, 6, 7] 18 | target1 = 7 19 | print(combinationSum(candidates1, target1)) # Output: [[2, 2, 3], [7]] 20 | 21 | candidates2 = [2, 3, 5] 22 | target2 = 8 23 | print(combinationSum(candidates2, target2)) # Output: [[2, 2, 2, 2], [2, 3, 3], [5]] 24 | 25 | candidates3 = [2] 26 | target3 = 1 27 | print(combinationSum(candidates3, target3)) # Output: [] 28 | -------------------------------------------------------------------------------- /My_Learning/Day_69/ques: -------------------------------------------------------------------------------- 1 | You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. 2 | 3 | Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: 4 | 5 | 0 <= j <= nums[i] and 6 | i + j < n 7 | Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1]. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [2,3,1,1,4] 14 | Output: 2 15 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 16 | Example 2: 17 | 18 | Input: nums = [2,3,0,1,4] 19 | Output: 2 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 104 25 | 0 <= nums[i] <= 1000 26 | It's guaranteed that you can reach nums[n - 1]. 27 | -------------------------------------------------------------------------------- /My_Learning/Day_13/Removes_Duplicates.py: -------------------------------------------------------------------------------- 1 | def removeDuplicates(nums): 2 | if not nums: 3 | return 0 4 | 5 | unique_index = 1 6 | 7 | # Iterate through the array to find unique elements 8 | for i in range(1, len(nums)): 9 | if nums[i] != nums[i - 1]: 10 | nums[unique_index] = nums[i] 11 | unique_index += 1 12 | 13 | return unique_index 14 | 15 | # Take user input for the array of integers 16 | try: 17 | nums = list(map(int, input("Enter a sorted array of integers separated by space: ").split())) 18 | 19 | # Remove duplicates in-place and get the number of unique elements 20 | k = removeDuplicates(nums) 21 | 22 | print("Number of unique elements:", k) 23 | print("Updated array:", nums[:k]) 24 | except ValueError: 25 | print("Invalid input. Please enter a valid sorted array of integers.") 26 | -------------------------------------------------------------------------------- /My_Learning/Day_15/SubArraySum.py: -------------------------------------------------------------------------------- 1 | def subarray_sum(nums, k): 2 | count = 0 3 | sum_so_far = 0 4 | sum_count = {0: 1} # To keep track of the sum and its count 5 | 6 | for num in nums: 7 | sum_so_far += num 8 | if sum_so_far - k in sum_count: 9 | count += sum_count[sum_so_far - k] 10 | 11 | if sum_so_far in sum_count: 12 | sum_count[sum_so_far] += 1 13 | else: 14 | sum_count[sum_so_far] = 1 15 | 16 | return count 17 | 18 | # Take user input for an array of integers 19 | user_input_nums = input("Enter a list of integers separated by space: ") 20 | nums = list(map(int, user_input_nums.replace(',', ' ').split())) 21 | 22 | # Take user input for the target sum k 23 | k = int(input("Enter the target sum k: ")) 24 | 25 | # Calculate and print the result 26 | result = subarray_sum(nums, k) 27 | print("Output:", result) 28 | 29 | -------------------------------------------------------------------------------- /My_Learning/Day_98/Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | roman_numerals = { 4 | 1000: 'M', 5 | 900: 'CM', 6 | 500: 'D', 7 | 400: 'CD', 8 | 100: 'C', 9 | 90: 'XC', 10 | 50: 'L', 11 | 40: 'XL', 12 | 10: 'X', 13 | 9: 'IX', 14 | 5: 'V', 15 | 4: 'IV', 16 | 1: 'I' 17 | } 18 | result = '' 19 | for value, symbol in roman_numerals.items(): 20 | while num >= value: 21 | result += symbol 22 | num -= value 23 | return result 24 | 25 | # Example usage 26 | sol = Solution() 27 | print(sol.intToRoman(3)) # Output: "III" 28 | print(sol.intToRoman(58)) # Output: "LVIII" 29 | print(sol.intToRoman(1994)) # Output: "MCMXCIV" 30 | -------------------------------------------------------------------------------- /My_Learning/Day_51/ques: -------------------------------------------------------------------------------- 1 | Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. 2 | 3 | According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. 4 | 5 | Example 1: 6 | 7 | Input: citations = [3,0,6,1,5] 8 | Output: 3 9 | Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. 10 | Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. 11 | Example 2: 12 | 13 | Input: citations = [1,3,1] 14 | Output: 1 15 | 16 | 17 | Constraints: 18 | 19 | n == citations.length 20 | 1 <= n <= 5000 21 | 0 <= citations[i] <= 1000 22 | -------------------------------------------------------------------------------- /My_Learning/Day_92/Heap.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import heapq 3 | 4 | def topKFrequent(nums, k): 5 | # Step 1: Count frequencies of each element 6 | freq = collections.Counter(nums) 7 | 8 | # Step 2: Use a min-heap to keep track of the k most frequent elements 9 | min_heap = [] 10 | 11 | for num, count in freq.items(): 12 | heapq.heappush(min_heap, (count, num)) 13 | if len(min_heap) > k: 14 | heapq.heappop(min_heap) 15 | 16 | # Step 3: Extract the k most frequent elements from the heap 17 | result = [] 18 | while min_heap: 19 | result.append(heapq.heappop(min_heap)[1]) 20 | 21 | # The result is in reverse order, so reverse it to get the correct order 22 | return result[::-1] 23 | 24 | # Test cases 25 | print(topKFrequent([1,1,1,2,2,3], 2)) # Output: [1,2] 26 | print(topKFrequent([1], 1)) # Output: [1] 27 | -------------------------------------------------------------------------------- /My_Learning/Day_28/isomorphic.py: -------------------------------------------------------------------------------- 1 | def isIsomorphic(s: str, t: str) -> bool: 2 | if len(s) != len(t): 3 | return False 4 | 5 | mapping_s_to_t = {} 6 | mapping_t_to_s = {} 7 | 8 | for char_s, char_t in zip(s, t): 9 | if char_s not in mapping_s_to_t: 10 | mapping_s_to_t[char_s] = char_t 11 | else: 12 | if mapping_s_to_t[char_s] != char_t: 13 | return False 14 | 15 | if char_t not in mapping_t_to_s: 16 | mapping_t_to_s[char_t] = char_s 17 | else: 18 | if mapping_t_to_s[char_t] != char_s: 19 | return False 20 | 21 | return True 22 | 23 | # Take user input for strings s and t 24 | s = input("Enter the first string (s): ") 25 | t = input("Enter the second string (t): ") 26 | 27 | # Call the function and print the result 28 | print("Output:", isIsomorphic(s, t)) 29 | -------------------------------------------------------------------------------- /My_Learning/Day_71/String_2_integer.py: -------------------------------------------------------------------------------- 1 | def myAtoi(s: str) -> int: 2 | if not s: 3 | return 0 4 | 5 | # Remove leading whitespace 6 | s = s.lstrip() 7 | 8 | # Check for empty string after removing whitespace 9 | if not s: 10 | return 0 11 | 12 | # Determine sign 13 | sign = 1 14 | if s[0] == '-': 15 | sign = -1 16 | s = s[1:] 17 | elif s[0] == '+': 18 | s = s[1:] 19 | 20 | # Read digits until a non-digit character is found 21 | result = 0 22 | for char in s: 23 | if char.isdigit(): 24 | result = result * 10 + int(char) 25 | else: 26 | break 27 | 28 | # Apply sign and clamp result to 32-bit integer range 29 | result *= sign 30 | result = max(min(result, 2**31 - 1), -2**31) 31 | 32 | return result 33 | 34 | # Example usage: 35 | s = input("Enter a string: ") 36 | print(myAtoi(s)) 37 | -------------------------------------------------------------------------------- /My_Learning/Day_56/ques: -------------------------------------------------------------------------------- 1 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | 3 | P A H N 4 | A P L S I I G 5 | Y I R 6 | And then read line by line: "PAHNAPLSIIGYIR" 7 | 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string s, int numRows); 11 | 12 | Example 1: 13 | 14 | Input: s = "PAYPALISHIRING", numRows = 3 15 | Output: "PAHNAPLSIIGYIR" 16 | Example 2: 17 | 18 | Input: s = "PAYPALISHIRING", numRows = 4 19 | Output: "PINALSIGYAHRPI" 20 | Explanation: 21 | P I N 22 | A L S I G 23 | Y A H R 24 | P I 25 | Example 3: 26 | 27 | Input: s = "A", numRows = 1 28 | Output: "A" 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= s.length <= 1000 34 | s consists of English letters (lower-case and upper-case), ',' and '.'. 35 | 1 <= numRows <= 1000 36 | -------------------------------------------------------------------------------- /My_Learning/Day_68/Permutation.py: -------------------------------------------------------------------------------- 1 | def permute(nums): 2 | def backtrack(current_permutation): 3 | if len(current_permutation) == len(nums): 4 | permutations.append(current_permutation[:]) # Make a copy of the permutation 5 | return 6 | 7 | for num in nums: 8 | if num not in current_permutation: 9 | current_permutation.append(num) 10 | backtrack(current_permutation) 11 | current_permutation.pop() 12 | 13 | permutations = [] 14 | backtrack([]) 15 | return permutations 16 | 17 | # Taking user input 18 | nums = list(map(int, input("Enter distinct integers separated by spaces: ").split())) 19 | 20 | # Check if the length of the input array is within the constraint 21 | if 1 <= len(nums) <= 6: 22 | result = permute(nums) 23 | print("All possible permutations:", result) 24 | else: 25 | print("Number of integers must be between 1 and 6.") 26 | -------------------------------------------------------------------------------- /My_Learning/Day_45/3SumClosest.py: -------------------------------------------------------------------------------- 1 | def threeSumClosest(nums, target): 2 | nums.sort() 3 | closest_sum = float('inf') 4 | n = len(nums) 5 | 6 | for i in range(n - 2): 7 | left, right = i + 1, n - 1 8 | while left < right: 9 | current_sum = nums[i] + nums[left] + nums[right] 10 | if abs(target - current_sum) < abs(target - closest_sum): 11 | closest_sum = current_sum 12 | if current_sum < target: 13 | left += 1 14 | elif current_sum > target: 15 | right -= 1 16 | else: 17 | return target # Found exact match, no need to continue 18 | return closest_sum 19 | 20 | # Test the function 21 | nums1 = [-1, 2, 1, -4] 22 | target1 = 1 23 | print(threeSumClosest(nums1, target1)) # Output: 2 24 | 25 | nums2 = [0, 0, 0] 26 | target2 = 1 27 | print(threeSumClosest(nums2, target2)) # Output: 0 28 | -------------------------------------------------------------------------------- /My_Learning/Day_49/ques: -------------------------------------------------------------------------------- 1 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | 3 | P A H N 4 | A P L S I I G 5 | Y I R 6 | And then read line by line: "PAHNAPLSIIGYIR" 7 | 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string s, int numRows); 11 | 12 | 13 | Example 1: 14 | 15 | Input: s = "PAYPALISHIRING", numRows = 3 16 | Output: "PAHNAPLSIIGYIR" 17 | Example 2: 18 | 19 | Input: s = "PAYPALISHIRING", numRows = 4 20 | Output: "PINALSIGYAHRPI" 21 | Explanation: 22 | P I N 23 | A L S I G 24 | Y A H R 25 | P I 26 | Example 3: 27 | 28 | Input: s = "A", numRows = 1 29 | Output: "A" 30 | 31 | 32 | Constraints: 33 | 34 | 1 <= s.length <= 1000 35 | s consists of English letters (lower-case and upper-case), ',' and '.'. 36 | 1 <= numRows <= 1000 37 | -------------------------------------------------------------------------------- /My_Learning/Day_34/ques: -------------------------------------------------------------------------------- 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 | Example 1: 3 | 4 | Input: nums = [3,0,1] 5 | Output: 2 6 | 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. 7 | Example 2: 8 | 9 | Input: nums = [0,1] 10 | Output: 2 11 | Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. 12 | Example 3: 13 | 14 | Input: nums = [9,6,4,2,3,5,7,0,1] 15 | Output: 8 16 | Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. 17 | 18 | 19 | Constraints: 20 | 21 | n == nums.length 22 | 1 <= n <= 104 23 | 0 <= nums[i] <= n 24 | All the numbers of nums are unique. 25 | -------------------------------------------------------------------------------- /My_Learning/Day_40/CombinationSum.py: -------------------------------------------------------------------------------- 1 | def combinationSum2(candidates, target): 2 | candidates.sort() 3 | result = [] 4 | 5 | def backtrack(start, target, path): 6 | if target == 0: 7 | result.append(path) 8 | return 9 | for i in range(start, len(candidates)): 10 | if i > start and candidates[i] == candidates[i - 1]: 11 | continue 12 | if candidates[i] > target: 13 | break 14 | backtrack(i + 1, target - candidates[i], path + [candidates[i]]) 15 | 16 | backtrack(0, target, []) 17 | return result 18 | 19 | # Example usage: 20 | candidates1 = [10, 1, 2, 7, 6, 1, 5] 21 | target1 = 8 22 | candidates2 = [2, 5, 2, 1, 2] 23 | target2 = 5 24 | 25 | print("Output for candidates1 and target1:", combinationSum2(candidates1, target1)) 26 | print("Output for candidates2 and target2:", combinationSum2(candidates2, target2)) 27 | -------------------------------------------------------------------------------- /My_Learning/Day_54/RightInterval.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | def findRightInterval(intervals): 4 | n = len(intervals) 5 | # Sort the intervals based on their start points 6 | sorted_intervals = sorted((interval[0], i) for i, interval in enumerate(intervals)) 7 | result = [-1] * n 8 | 9 | for i, interval in enumerate(intervals): 10 | end_point = interval[1] 11 | # Perform binary search to find the right interval 12 | index = bisect.bisect_left(sorted_intervals, (end_point,)) 13 | if index < n: 14 | result[i] = sorted_intervals[index][1] 15 | 16 | return result 17 | 18 | # Test cases 19 | intervals1 = [[1,2]] 20 | intervals2 = [[3,4],[2,3],[1,2]] 21 | intervals3 = [[1,4],[2,3],[3,4]] 22 | 23 | print(findRightInterval(intervals1)) # Output: [-1] 24 | print(findRightInterval(intervals2)) # Output: [-1, 0, 1] 25 | print(findRightInterval(intervals3)) # Output: [-1, 2, -1] 26 | -------------------------------------------------------------------------------- /My_Learning/Day_78/BagofTokens.py: -------------------------------------------------------------------------------- 1 | def bagOfTokensScore(tokens, power): 2 | tokens.sort() 3 | left = 0 4 | right = len(tokens) - 1 5 | score = 0 6 | max_score = 0 7 | 8 | while left <= right: 9 | if power >= tokens[left]: 10 | power -= tokens[left] 11 | score += 1 12 | left += 1 13 | max_score = max(max_score, score) 14 | elif score > 0: 15 | power += tokens[right] 16 | score -= 1 17 | right -= 1 18 | else: 19 | break 20 | 21 | return max_score 22 | 23 | # Test cases 24 | tokens1 = [100] 25 | power1 = 50 26 | print(bagOfTokensScore(tokens1, power1)) # Output: 0 27 | 28 | tokens2 = [200, 100] 29 | power2 = 150 30 | print(bagOfTokensScore(tokens2, power2)) # Output: 1 31 | 32 | tokens3 = [100, 200, 300, 400] 33 | power3 = 200 34 | print(bagOfTokensScore(tokens3, power3)) # Output: 2 35 | -------------------------------------------------------------------------------- /My_Learning/Day_25/ques: -------------------------------------------------------------------------------- 1 | There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. 2 | 3 | You are giving candies to these children subjected to the following requirements: 4 | 5 | Each child must have at least one candy. 6 | Children with a higher rating get more candies than their neighbors. 7 | Return the minimum number of candies you need to have to distribute the candies to the children. 8 | 9 | Example 1: 10 | 11 | Input: ratings = [1,0,2] 12 | Output: 5 13 | Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. 14 | Example 2: 15 | 16 | Input: ratings = [1,2,2] 17 | Output: 4 18 | Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. 19 | The third child gets 1 candy because it satisfies the above two conditions. 20 | 21 | Constraints: 22 | 23 | n == ratings.length 24 | 1 <= n <= 2 * 104 25 | 0 <= ratings[i] <= 2 * 104 26 | -------------------------------------------------------------------------------- /My_Learning/Day_76/SortedMatrix.py: -------------------------------------------------------------------------------- 1 | def kthSmallest(matrix, k): 2 | n = len(matrix) 3 | left, right = matrix[0][0], matrix[n - 1][n - 1] 4 | 5 | def count_less_equal(mid): 6 | count = 0 7 | row, col = n - 1, 0 8 | while row >= 0 and col < n: 9 | if matrix[row][col] <= mid: 10 | count += row + 1 11 | col += 1 12 | else: 13 | row -= 1 14 | return count 15 | 16 | while left < right: 17 | mid = left + (right - left) // 2 18 | count = count_less_equal(mid) 19 | if count < k: 20 | left = mid + 1 21 | else: 22 | right = mid 23 | 24 | return left 25 | 26 | # Example usage: 27 | matrix1 = [ 28 | [1, 5, 9], 29 | [10, 11, 13], 30 | [12, 13, 15] 31 | ] 32 | k1 = 8 33 | print(kthSmallest(matrix1, k1)) # Output: 13 34 | 35 | matrix2 = [[-5]] 36 | k2 = 1 37 | print(kthSmallest(matrix2, k2)) # Output: -5 38 | -------------------------------------------------------------------------------- /My_Learning/Day_27/3_sum.py: -------------------------------------------------------------------------------- 1 | def find_triplet(arr, target_sum): 2 | n = len(arr) 3 | arr.sort() 4 | 5 | for i in range(n - 2): 6 | left = i + 1 7 | right = n - 1 8 | 9 | while left < right: 10 | current_sum = arr[i] + arr[left] + arr[right] 11 | if current_sum == target_sum: 12 | return arr[i], arr[left], arr[right] 13 | elif current_sum < target_sum: 14 | left += 1 15 | else: 16 | right -= 1 17 | 18 | return None 19 | 20 | # Take user input for array elements 21 | arr = list(map(int, input("Enter the array elements separated by space: ").split())) 22 | 23 | # Take user input for the target sum 24 | target_sum = int(input("Enter the target sum: ")) 25 | 26 | result = find_triplet(arr, target_sum) 27 | 28 | if result: 29 | print("Triplet found:", result) 30 | else: 31 | print("No triplet found for the given sum.") 32 | -------------------------------------------------------------------------------- /My_Learning/Day_39/ques: -------------------------------------------------------------------------------- 1 | A peak element is an element that is strictly greater than its neighbors. 2 | 3 | Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. 4 | 5 | You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. 6 | 7 | You must write an algorithm that runs in O(log n) time. 8 | 9 | Example 1: 10 | 11 | Input: nums = [1,2,3,1] 12 | Output: 2 13 | Explanation: 3 is a peak element and your function should return the index number 2. 14 | Example 2: 15 | 16 | Input: nums = [1,2,1,3,5,6,4] 17 | Output: 5 18 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. 19 | 20 | Constraints: 21 | 22 | 1 <= nums.length <= 1000 23 | -231 <= nums[i] <= 231 - 1 24 | nums[i] != nums[i + 1] for all valid i. 25 | -------------------------------------------------------------------------------- /My_Learning/Day_35/Longest_Repeating_Character_Replacement.py: -------------------------------------------------------------------------------- 1 | def characterReplacement(s: str, k: int) -> int: 2 | max_length = 0 3 | start = 0 4 | max_count = 0 5 | count = {} 6 | 7 | for end in range(len(s)): 8 | count[s[end]] = count.get(s[end], 0) + 1 9 | max_count = max(max_count, count[s[end]]) 10 | 11 | # If the current window size minus the count of the most frequent character 12 | # exceeds the allowed operations (k), we need to shrink the window 13 | if end - start + 1 - max_count > k: 14 | count[s[start]] -= 1 15 | start += 1 16 | 17 | max_length = max(max_length, end - start + 1) 18 | 19 | return max_length 20 | 21 | # Take user input for the string s 22 | s = input("Enter the string s: ") 23 | 24 | # Take user input for k 25 | k = int(input("Enter the value of k: ")) 26 | 27 | # Call the function and print the result 28 | print("Output:", characterReplacement(s, k)) 29 | -------------------------------------------------------------------------------- /My_Learning/Day_27/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 2 | 3 | Notice that the solution set must not contain duplicate triplets. 4 | 5 | Example 1: 6 | 7 | Input: nums = [-1,0,1,2,-1,-4] 8 | Output: [[-1,-1,2],[-1,0,1]] 9 | Explanation: 10 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 11 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 12 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 13 | The distinct triplets are [-1,0,1] and [-1,-1,2]. 14 | Notice that the order of the output and the order of the triplets does not matter. 15 | Example 2: 16 | 17 | Input: nums = [0,1,1] 18 | Output: [] 19 | Explanation: The only possible triplet does not sum up to 0. 20 | Example 3: 21 | 22 | Input: nums = [0,0,0] 23 | Output: [[0,0,0]] 24 | Explanation: The only possible triplet sums up to 0. 25 | 26 | Constraints: 27 | 28 | 3 <= nums.length <= 3000 29 | -105 <= nums[i] <= 105 30 | -------------------------------------------------------------------------------- /My_Learning/Day_89/Wildcard_matching.py: -------------------------------------------------------------------------------- 1 | def isMatch(s: str, p: str) -> bool: 2 | # Initialize the dynamic programming table 3 | dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] 4 | 5 | # Empty pattern matches empty string 6 | dp[0][0] = True 7 | 8 | # Handle patterns that start with '*' 9 | for j in range(1, len(p) + 1): 10 | if p[j - 1] == '*': 11 | dp[0][j] = dp[0][j - 1] 12 | 13 | # Fill the dynamic programming table 14 | for i in range(1, len(s) + 1): 15 | for j in range(1, len(p) + 1): 16 | if p[j - 1] == '*' : 17 | dp[i][j] = dp[i][j - 1] or dp[i - 1][j] 18 | elif p[j - 1] == '?' or s[i - 1] == p[j - 1]: 19 | dp[i][j] = dp[i - 1][j - 1] 20 | 21 | # Return the result 22 | return dp[len(s)][len(p)] 23 | 24 | # Test cases 25 | print(isMatch("aa", "a")) # Output: False 26 | print(isMatch("aa", "*")) # Output: True 27 | print(isMatch("cb", "?a")) # Output: False 28 | -------------------------------------------------------------------------------- /My_Learning/Day_88/+veNumber.py: -------------------------------------------------------------------------------- 1 | def firstMissingPositive(nums): 2 | n = len(nums) 3 | 4 | # Rearrange the array such that all positive integers [1, n] are placed in their correct positions 5 | for i in range(n): 6 | # While nums[i] is a positive integer within the range [1, n] and nums[i] is not in its correct position 7 | while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: 8 | # Swap nums[i] to its correct position nums[nums[i] - 1] 9 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] 10 | 11 | # Find the first missing positive integer 12 | for i in range(n): 13 | if nums[i] != i + 1: 14 | return i + 1 15 | 16 | # If all positive integers [1, n] are present, return n + 1 17 | return n + 1 18 | 19 | # Test cases 20 | print(firstMissingPositive([1, 2, 0])) # Output: 3 21 | print(firstMissingPositive([3, 4, -1, 1])) # Output: 2 22 | print(firstMissingPositive([7, 8, 9, 11, 12])) # Output: 1 23 | -------------------------------------------------------------------------------- /My_Learning/Day_26/ques: -------------------------------------------------------------------------------- 1 | Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. 2 | 3 | Note that the same word in the dictionary may be reused multiple times in the segmentation. 4 | 5 | Example 1: 6 | 7 | Input: s = "leetcode", wordDict = ["leet","code"] 8 | Output: true 9 | Explanation: Return true because "leetcode" can be segmented as "leet code". 10 | Example 2: 11 | 12 | Input: s = "applepenapple", wordDict = ["apple","pen"] 13 | Output: true 14 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 15 | Note that you are allowed to reuse a dictionary word. 16 | Example 3: 17 | 18 | Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] 19 | Output: false 20 | 21 | Constraints: 22 | 23 | 1 <= s.length <= 300 24 | 1 <= wordDict.length <= 1000 25 | 1 <= wordDict[i].length <= 20 26 | s and wordDict[i] consist of only lowercase English letters. 27 | All the strings of wordDict are unique. 28 | -------------------------------------------------------------------------------- /My_Learning/Day_89/ques: -------------------------------------------------------------------------------- 1 | 2 | Code 3 | Testcase 4 | Test Result 5 | Test Result 6 | 44. Wildcard Matching 7 | Hard 8 | Topics 9 | Companies 10 | Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: 11 | 12 | '?' Matches any single character. 13 | '*' Matches any sequence of characters (including the empty sequence). 14 | The matching should cover the entire input string (not partial). 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: s = "aa", p = "a" 21 | Output: false 22 | Explanation: "a" does not match the entire string "aa". 23 | Example 2: 24 | 25 | Input: s = "aa", p = "*" 26 | Output: true 27 | Explanation: '*' matches any sequence. 28 | Example 3: 29 | 30 | Input: s = "cb", p = "?a" 31 | Output: false 32 | Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. 33 | 34 | 35 | Constraints: 36 | 37 | 0 <= s.length, p.length <= 2000 38 | s contains only lowercase English letters. 39 | p contains only lowercase English letters, '?' or '*'. 40 | -------------------------------------------------------------------------------- /My_Learning/Day_77/CoinChange.py: -------------------------------------------------------------------------------- 1 | def coinChange(coins, amount): 2 | # Initialize dp array with float('inf') (indicating impossible) 3 | dp = [float('inf')] * (amount + 1) 4 | dp[0] = 0 # Zero coins needed to make amount 0 5 | 6 | # Process each coin denomination 7 | for coin in coins: 8 | for j in range(coin, amount + 1): 9 | if dp[j - coin] != float('inf'): 10 | dp[j] = min(dp[j], dp[j - coin] + 1) 11 | 12 | # Return the fewest number of coins needed for amount 13 | return dp[amount] if dp[amount] != float('inf') else -1 14 | 15 | # Test the function with examples 16 | coins1 = [1, 2, 5] 17 | amount1 = 11 18 | print(coinChange(coins1, amount1)) # Output: 3 (11 = 5 + 5 + 1) 19 | 20 | coins2 = [2] 21 | amount2 = 3 22 | print(coinChange(coins2, amount2)) # Output: -1 (Cannot make up amount 3 with coin denomination [2]) 23 | 24 | coins3 = [1] 25 | amount3 = 0 26 | print(coinChange(coins3, amount3)) # Output: 0 (No coins needed to make up amount 0) 27 | -------------------------------------------------------------------------------- /My_Learning/Day_67/ques: -------------------------------------------------------------------------------- 1 | Design your implementation of the circular double-ended queue (deque). 2 | 3 | Implement the MyCircularDeque class: 4 | 5 | MyCircularDeque(int k) Initializes the deque with a maximum size of k. 6 | boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise. 7 | boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise. 8 | boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise. 9 | boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise. 10 | int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. 11 | int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. 12 | boolean isEmpty() Returns true if the deque is empty, or false otherwise. 13 | boolean isFull() Returns true if the deque is full, or false otherwise. 14 | -------------------------------------------------------------------------------- /My_Learning/Day_19/ques: -------------------------------------------------------------------------------- 1 | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: 2 | 3 | '.' Matches any single character.​​​​ 4 | '*' Matches zero or more of the preceding element. 5 | The matching should cover the entire input string (not partial). 6 | Example 1: 7 | 8 | Input: s = "aa", p = "a" 9 | Output: false 10 | Explanation: "a" does not match the entire string "aa". 11 | Example 2: 12 | 13 | Input: s = "aa", p = "a*" 14 | Output: true 15 | Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". 16 | Example 3: 17 | 18 | Input: s = "ab", p = ".*" 19 | Output: true 20 | Explanation: ".*" means "zero or more (*) of any character (.)". 21 | 22 | Constraints: 23 | 24 | 1 <= s.length <= 20 25 | 1 <= p.length <= 20 26 | s contains only lowercase English letters. 27 | p contains only lowercase English letters, '.', and '*'. 28 | It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. 29 | -------------------------------------------------------------------------------- /My_Learning/Day_58/ques: -------------------------------------------------------------------------------- 1 | Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. 2 | 3 | The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. 4 | 5 | Return the quotient after dividing dividend by divisor. 6 | 7 | Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: dividend = 10, divisor = 3 14 | Output: 3 15 | Explanation: 10/3 = 3.33333.. which is truncated to 3. 16 | Example 2: 17 | 18 | Input: dividend = 7, divisor = -3 19 | Output: -2 20 | Explanation: 7/-3 = -2.33333.. which is truncated to -2. 21 | 22 | 23 | Constraints: 24 | 25 | -231 <= dividend, divisor <= 231 - 1 26 | divisor != 0 27 | -------------------------------------------------------------------------------- /My_Learning/Day_43/DesignBitset.py: -------------------------------------------------------------------------------- 1 | class Bitset: 2 | def __init__(self, size): 3 | self.size = size 4 | self.bits = [0] * size 5 | 6 | def fix(self, idx): 7 | if 0 <= idx < self.size: 8 | self.bits[idx] = 1 9 | 10 | def unfix(self, idx): 11 | if 0 <= idx < self.size: 12 | self.bits[idx] = 0 13 | 14 | def flip(self): 15 | for i in range(self.size): 16 | self.bits[i] ^= 1 17 | 18 | def all(self): 19 | return all(self.bits) 20 | 21 | def one(self): 22 | return any(self.bits) 23 | 24 | def count(self): 25 | return sum(self.bits) 26 | 27 | def toString(self): 28 | return ''.join(map(str, self.bits)) 29 | 30 | 31 | # Example 32 | bs = Bitset(5) 33 | bs.fix(3) 34 | bs.fix(1) 35 | bs.flip() 36 | print("all:", bs.all()) 37 | bs.unfix(0) 38 | bs.flip() 39 | print("one:", bs.one()) 40 | bs.unfix(0) 41 | print("count:", bs.count()) 42 | print("toString:", bs.toString()) 43 | -------------------------------------------------------------------------------- /My_Learning/Day_72/LeftLeave.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | 7 | def sumOfLeftLeaves(root): 8 | if not root: 9 | return 0 10 | 11 | def is_leaf(node): 12 | return node and not node.left and not node.right 13 | 14 | def dfs(node): 15 | total_sum = 0 16 | if node.left: 17 | if is_leaf(node.left): # Check if left child is a leaf 18 | total_sum += node.left.val 19 | else: 20 | total_sum += dfs(node.left) # Traverse left subtree 21 | if node.right: 22 | total_sum += dfs(node.right) # Traverse right subtree 23 | return total_sum 24 | 25 | return dfs(root) 26 | 27 | root = TreeNode(3) 28 | root.left = TreeNode(9) 29 | root.right = TreeNode(20) 30 | root.right.left = TreeNode(15) 31 | root.right.right = TreeNode(7) 32 | 33 | print(sumOfLeftLeaves(root)) # Output: 24 (9 + 15) 34 | -------------------------------------------------------------------------------- /My_Learning/Day_31/ques: -------------------------------------------------------------------------------- 1 | An n-bit gray code sequence is a sequence of 2n integers where: 2 | 3 | Every integer is in the inclusive range [0, 2n - 1], 4 | The first integer is 0, 5 | An integer appears no more than once in the sequence, 6 | The binary representation of every pair of adjacent integers differs by exactly one bit, and 7 | The binary representation of the first and last integers differs by exactly one bit. 8 | Given an integer n, return any valid n-bit gray code sequence. 9 | 10 | Example 1: 11 | 12 | Input: n = 2 13 | Output: [0,1,3,2] 14 | Explanation: 15 | The binary representation of [0,1,3,2] is [00,01,11,10]. 16 | - 00 and 01 differ by one bit 17 | - 01 and 11 differ by one bit 18 | - 11 and 10 differ by one bit 19 | - 10 and 00 differ by one bit 20 | [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. 21 | - 00 and 10 differ by one bit 22 | - 10 and 11 differ by one bit 23 | - 11 and 01 differ by one bit 24 | - 01 and 00 differ by one bit 25 | Example 2: 26 | 27 | Input: n = 1 28 | Output: [0,1] 29 | 30 | Constraints: 31 | 32 | 1 <= n <= 16 33 | -------------------------------------------------------------------------------- /My_Learning/Day_60/3Sum_Closet.py: -------------------------------------------------------------------------------- 1 | def three_sum_closest(nums, target): 2 | nums.sort() # Sort the array to use two-pointer approach 3 | closest_sum = float('inf') # Initialize closest sum to infinity 4 | 5 | for i in range(len(nums) - 2): 6 | left, right = i + 1, len(nums) - 1 # Pointers for two sum 7 | while left < right: 8 | current_sum = nums[i] + nums[left] + nums[right] 9 | if abs(target - current_sum) < abs(target - closest_sum): 10 | closest_sum = current_sum 11 | if current_sum < target: 12 | left += 1 13 | elif current_sum > target: 14 | right -= 1 15 | else: 16 | return closest_sum # If found exact target, return early 17 | 18 | return closest_sum 19 | 20 | # User input 21 | nums = list(map(int, input("Enter the array elements separated by space: ").split())) 22 | target = int(input("Enter the target sum: ")) 23 | 24 | # Call the function and print the result 25 | result = three_sum_closest(nums, target) 26 | print("The sum closest to the target is:", result) 27 | -------------------------------------------------------------------------------- /My_Learning/Day_37/MinStack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.stack = [] 8 | self.min_stack = [] 9 | 10 | def push(self, val: int) -> None: 11 | self.stack.append(val) 12 | if not self.min_stack or val <= self.min_stack[-1]: 13 | self.min_stack.append(val) 14 | 15 | def pop(self) -> None: 16 | if self.stack: 17 | popped = self.stack.pop() 18 | if popped == self.min_stack[-1]: 19 | self.min_stack.pop() 20 | 21 | def top(self) -> int: 22 | if self.stack: 23 | return self.stack[-1] 24 | 25 | def getMin(self) -> int: 26 | if self.min_stack: 27 | return self.min_stack[-1] 28 | 29 | 30 | # Example usage: 31 | minStack = MinStack() 32 | minStack.push(-2) 33 | minStack.push(0) 34 | minStack.push(-3) 35 | print(minStack.getMin()) # Output: -3 36 | minStack.pop() 37 | print(minStack.top()) # Output: 0 38 | print(minStack.getMin()) # Output: -2 39 | -------------------------------------------------------------------------------- /My_Learning/Day_44/ques: -------------------------------------------------------------------------------- 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 | Example 1: 6 | 7 | Input: digits = [1,2,3] 8 | Output: [1,2,4] 9 | Explanation: The array represents the integer 123. 10 | Incrementing by one gives 123 + 1 = 124. 11 | Thus, the result should be [1,2,4]. 12 | Example 2: 13 | 14 | Input: digits = [4,3,2,1] 15 | Output: [4,3,2,2] 16 | Explanation: The array represents the integer 4321. 17 | Incrementing by one gives 4321 + 1 = 4322. 18 | Thus, the result should be [4,3,2,2]. 19 | Example 3: 20 | 21 | Input: digits = [9] 22 | Output: [1,0] 23 | Explanation: The array represents the integer 9. 24 | Incrementing by one gives 9 + 1 = 10. 25 | Thus, the result should be [1,0]. 26 | 27 | Constraints: 28 | 29 | 1 <= digits.length <= 100 30 | 0 <= digits[i] <= 9 31 | digits does not contain any leading 0's. 32 | -------------------------------------------------------------------------------- /My_Learning/Day_85/InterleavingString.py: -------------------------------------------------------------------------------- 1 | def isInterleave(s1, s2, s3): 2 | m, n = len(s1), len(s2) 3 | 4 | # If lengths of s1 and s2 don't add up to length of s3, return False 5 | if m + n != len(s3): 6 | return False 7 | 8 | # dp[i][j] represents if s3[0...i+j-1] can be formed by the interleaving of s1[0...i-1] and s2[0...j-1] 9 | dp = [[False] * (n + 1) for _ in range(m + 1)] 10 | 11 | # Base case: empty strings can form an empty string 12 | dp[0][0] = True 13 | 14 | # Fill the dp table 15 | for i in range(m + 1): 16 | for j in range(n + 1): 17 | if i > 0 and s1[i - 1] == s3[i + j - 1]: 18 | dp[i][j] = dp[i][j] or dp[i - 1][j] 19 | if j > 0 and s2[j - 1] == s3[i + j - 1]: 20 | dp[i][j] = dp[i][j] or dp[i][j - 1] 21 | 22 | return dp[m][n] 23 | 24 | # Test cases 25 | print(isInterleave("aabcc", "dbbca", "aadbbcbcac")) # Output: True 26 | print(isInterleave("aabcc", "dbbca", "aadbbbaccc")) # Output: False 27 | print(isInterleave("", "", "")) # Output: True 28 | -------------------------------------------------------------------------------- /My_Learning/Day_38/ques.txt: -------------------------------------------------------------------------------- 1 | Given an encoded string, return its decoded string. 2 | 3 | The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. 4 | 5 | You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. 6 | 7 | The test cases are generated so that the length of the output will never exceed 105. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: s = "3[a]2[bc]" 14 | Output: "aaabcbc" 15 | Example 2: 16 | 17 | Input: s = "3[a2[c]]" 18 | Output: "accaccacc" 19 | Example 3: 20 | 21 | Input: s = "2[abc]3[cd]ef" 22 | Output: "abcabccdcdcdef" 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= s.length <= 30 28 | s consists of lowercase English letters, digits, and square brackets '[]'. 29 | s is guaranteed to be a valid input. 30 | All the integers in s are in the range [1, 300]. 31 | -------------------------------------------------------------------------------- /My_Learning/Day_99/Calculator.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculate(self, s: str) -> int: 3 | stack = [] 4 | num = 0 5 | result = 0 6 | sign = 1 7 | 8 | for char in s: 9 | if char.isdigit(): 10 | num = num * 10 + int(char) 11 | elif char in ['+', '-']: 12 | result += sign * num 13 | num = 0 14 | sign = 1 if char == '+' else -1 15 | elif char == '(': 16 | stack.append((result, sign)) 17 | result = 0 18 | sign = 1 19 | elif char == ')': 20 | prev_result, prev_sign = stack.pop() 21 | result += sign * num 22 | result *= prev_sign 23 | result += prev_result 24 | num = 0 25 | 26 | return result + sign * num 27 | 28 | # Example usage 29 | sol = Solution() 30 | print(sol.calculate("1 + 1")) # Output: 2 31 | print(sol.calculate(" 2-1 + 2 ")) # Output: 3 32 | print(sol.calculate("(1+(4+5+2)-3)+(6+8)")) # Output: 23 33 | -------------------------------------------------------------------------------- /My_Learning/Day_87/VersionNumber.py: -------------------------------------------------------------------------------- 1 | def compareVersion(version1, version2): 2 | # Split the versions into their respective parts 3 | parts1 = version1.split('.') 4 | parts2 = version2.split('.') 5 | 6 | # Compare revisions 7 | for i in range(max(len(parts1), len(parts2))): 8 | # Get the integer value of the revision (or treat missing revisions as 0) 9 | num1 = int(parts1[i]) if i < len(parts1) else 0 10 | num2 = int(parts2[i]) if i < len(parts2) else 0 11 | 12 | # Compare the integer values 13 | if num1 < num2: 14 | return -1 15 | elif num1 > num2: 16 | return 1 17 | 18 | # All revisions compared are equal, compare lengths of revision arrays 19 | if len(parts1) > len(parts2): 20 | return 1 21 | elif len(parts1) < len(parts2): 22 | return -1 23 | 24 | # If no difference found, return 0 25 | return 0 26 | 27 | # Test cases 28 | print(compareVersion("1.01", "1.001")) # Output: 0 29 | print(compareVersion("1.0", "1.0.0")) # Output: 0 30 | print(compareVersion("0.1", "1.1")) # Output: -1 31 | -------------------------------------------------------------------------------- /My_Learning/Day_53/ques: -------------------------------------------------------------------------------- 1 | Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. 2 | 3 | Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. 4 | 5 | After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. 6 | 7 | Example 8 | 9 | Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] 10 | Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] 11 | -------------------------------------------------------------------------------- /My_Learning/Day_98/ques: -------------------------------------------------------------------------------- 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 one's 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 | 19 | Given an integer, convert it to a roman numeral. 20 | Example : 21 | Input: num = 3 22 | Output: "III" 23 | 24 | Constraints: 25 | 1 <= num <= 3999 26 | -------------------------------------------------------------------------------- /My_Learning/Day_91/ScrambleString.py: -------------------------------------------------------------------------------- 1 | def isScramble(s1, s2): 2 | # Memoization dictionary 3 | memo = {} 4 | 5 | def scramble(s1, s2): 6 | # Base cases 7 | if (s1, s2) in memo: 8 | return memo[(s1, s2)] 9 | 10 | if s1 == s2: 11 | memo[(s1, s2)] = True 12 | return True 13 | 14 | if sorted(s1) != sorted(s2): 15 | memo[(s1, s2)] = False 16 | return False 17 | 18 | n = len(s1) 19 | 20 | # Check all possible split points 21 | for i in range(1, n): 22 | if (scramble(s1[:i], s2[:i]) and scramble(s1[i:], s2[i:])) or \ 23 | (scramble(s1[:i], s2[-i:]) and scramble(s1[i:], s2[:-i])): 24 | memo[(s1, s2)] = True 25 | return True 26 | 27 | memo[(s1, s2)] = False 28 | return False 29 | 30 | return scramble(s1, s2) 31 | 32 | # Test cases 33 | print(isScramble("great", "rgeat")) # Output: True 34 | print(isScramble("abcde", "caebd")) # Output: False 35 | print(isScramble("a", "a")) # Output: True 36 | -------------------------------------------------------------------------------- /My_Learning/Day_37/ques: -------------------------------------------------------------------------------- 1 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 2 | 3 | Implement the MinStack class: 4 | 5 | MinStack() initializes the stack object. 6 | void push(int val) pushes the element val onto the stack. 7 | void pop() removes the element on the top of the stack. 8 | int top() gets the top element of the stack. 9 | int getMin() retrieves the minimum element in the stack. 10 | You must implement a solution with O(1) time complexity for each function. 11 | 12 | Example 1: 13 | 14 | Input 15 | ["MinStack","push","push","push","getMin","pop","top","getMin"] 16 | [[],[-2],[0],[-3],[],[],[],[]] 17 | 18 | Output 19 | [null,null,null,null,-3,null,0,-2] 20 | 21 | Explanation 22 | MinStack minStack = new MinStack(); 23 | minStack.push(-2); 24 | minStack.push(0); 25 | minStack.push(-3); 26 | minStack.getMin(); // return -3 27 | minStack.pop(); 28 | minStack.top(); // return 0 29 | minStack.getMin(); // return -2 30 | 31 | Constraints: 32 | 33 | -231 <= val <= 231 - 1 34 | Methods pop, top and getMin operations will always be called on non-empty stacks. 35 | At most 3 * 104 calls will be made to push, pop, top, and getMin. 36 | -------------------------------------------------------------------------------- /My_Learning/Day_59/ques: -------------------------------------------------------------------------------- 1 | Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. 2 | 3 | The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the 4 | frequency 5 | of at least one of the chosen numbers is different. 6 | 7 | The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. 8 | 9 | Example 1: 10 | 11 | Input: candidates = [2,3,6,7], target = 7 12 | Output: [[2,2,3],[7]] 13 | Explanation: 14 | 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 15 | 7 is a candidate, and 7 = 7. 16 | These are the only two combinations. 17 | Example 2: 18 | 19 | Input: candidates = [2,3,5], target = 8 20 | Output: [[2,2,2,2],[2,3,3],[3,5]] 21 | Example 3: 22 | 23 | Input: candidates = [2], target = 1 24 | Output: [] 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= candidates.length <= 30 30 | 2 <= candidates[i] <= 40 31 | All elements of candidates are distinct. 32 | 1 <= target <= 40 33 | -------------------------------------------------------------------------------- /My_Learning/Day_1: -------------------------------------------------------------------------------- 1 | Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. 2 | 3 | It is used for: 4 | 5 | - web development (server-side), 6 | - software development, 7 | - mathematics, 8 | - system scripting. 9 | 10 | # #What can Python do? 11 | 12 | - Python can be used on a server to create web applications. 13 | - Python can be used alongside software to create workflows. 14 | - Python can connect to database systems. It can also read and modify files. 15 | - Python can be used to handle big data and perform complex mathematics. 16 | - Python can be used for rapid prototyping, or for production-ready software development. 17 | 18 | # #Why Python? 19 | 20 | - Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). 21 | - Python has a simple syntax similar to the English language. 22 | - Python has syntax that allows developers to write programs with fewer lines than some other programming languages. 23 | - Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. 24 | - Python can be treated in a procedural way, an object-oriented way or a functional way. 25 | -------------------------------------------------------------------------------- /My_Learning/Day_70/BinaryTree.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | 7 | def levelOrder(root): 8 | if not root: 9 | return [] 10 | 11 | result = [] 12 | queue = [root] 13 | 14 | while queue: 15 | level = [] 16 | level_size = len(queue) 17 | for _ in range(level_size): 18 | node = queue.pop(0) 19 | level.append(node.val) 20 | if node.left: 21 | queue.append(node.left) 22 | if node.right: 23 | queue.append(node.right) 24 | result.append(level) 25 | 26 | return result 27 | 28 | # Example usage: 29 | # Example 1: 30 | root1 = TreeNode(3) 31 | root1.left = TreeNode(9) 32 | root1.right = TreeNode(20) 33 | root1.right.left = TreeNode(15) 34 | root1.right.right = TreeNode(7) 35 | 36 | print(levelOrder(root1)) # Output: [[3], [9, 20], [15, 7]] 37 | 38 | # Example 2: 39 | root2 = TreeNode(1) 40 | print(levelOrder(root2)) # Output: [[1]] 41 | 42 | # Example 3: 43 | root3 = None 44 | print(levelOrder(root3)) # Output: [] 45 | -------------------------------------------------------------------------------- /My_Learning/Day_36/WordLadder.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def ladderLength(beginWord, endWord, wordList): 4 | word_set = set(wordList) 5 | if endWord not in word_set: 6 | return 0 7 | 8 | queue = deque([(beginWord, 1)]) 9 | visited = set([beginWord]) 10 | 11 | while queue: 12 | current_word, level = queue.popleft() 13 | if current_word == endWord: 14 | return level 15 | for i in range(len(current_word)): 16 | for char in 'abcdefghijklmnopqrstuvwxyz': 17 | next_word = current_word[:i] + char + current_word[i+1:] 18 | if next_word in word_set and next_word not in visited: 19 | queue.append((next_word, level + 1)) 20 | visited.add(next_word) 21 | 22 | return 0 23 | 24 | # Take user input for beginWord, endWord, and wordList 25 | beginWord = input("Enter the beginWord: ") 26 | endWord = input("Enter the endWord: ") 27 | wordList = input("Enter the wordList separated by space: ").split() 28 | 29 | # Find the number of words in the shortest transformation sequence 30 | result = ladderLength(beginWord, endWord, wordList) 31 | print("Output:", result) -------------------------------------------------------------------------------- /My_Learning/Day_47/InsertInterval.py: -------------------------------------------------------------------------------- 1 | def insertInterval(intervals, newInterval): 2 | merged = [] 3 | i = 0 4 | n = len(intervals) 5 | 6 | # Add all intervals that end before the new interval starts 7 | while i < n and intervals[i][1] < newInterval[0]: 8 | merged.append(intervals[i]) 9 | i += 1 10 | 11 | # Merge intervals that overlap with the new interval 12 | while i < n and intervals[i][0] <= newInterval[1]: 13 | newInterval[0] = min(newInterval[0], intervals[i][0]) 14 | newInterval[1] = max(newInterval[1], intervals[i][1]) 15 | i += 1 16 | 17 | merged.append(newInterval) # Add the merged interval 18 | 19 | # Add all intervals that start after the new interval ends 20 | while i < n: 21 | merged.append(intervals[i]) 22 | i += 1 23 | 24 | return merged 25 | 26 | # Test the function 27 | intervals1 = [[1,3],[6,9]] 28 | newInterval1 = [2,5] 29 | print(insertInterval(intervals1, newInterval1)) # Output: [[1,5],[6,9]] 30 | 31 | intervals2 = [[1,2],[3,5],[6,7],[8,10],[12,16]] 32 | newInterval2 = [4,8] 33 | print(insertInterval(intervals2, newInterval2)) # Output: [[1,2],[3,10],[12,16]] 34 | -------------------------------------------------------------------------------- /My_Learning/Day_61/SwapNodes.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def swapPairs(head): 7 | dummy = ListNode(0) 8 | dummy.next = head 9 | prev = dummy 10 | 11 | while prev.next and prev.next.next: 12 | first_node = prev.next 13 | second_node = prev.next.next 14 | 15 | prev.next = second_node 16 | first_node.next = second_node.next 17 | second_node.next = first_node 18 | 19 | prev = first_node 20 | 21 | return dummy.next 22 | 23 | def printLinkedList(head): 24 | current = head 25 | while current: 26 | print(current.val, end=" -> ") 27 | current = current.next 28 | print("None") 29 | 30 | # Example usage: 31 | # Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 32 | head = ListNode(1) 33 | head.next = ListNode(2) 34 | head.next.next = ListNode(3) 35 | head.next.next.next = ListNode(4) 36 | head.next.next.next.next = ListNode(5) 37 | 38 | print("Original linked list:") 39 | printLinkedList(head) 40 | 41 | new_head = swapPairs(head) 42 | 43 | print("\nLinked list after swapping pairs:") 44 | printLinkedList(new_head) 45 | -------------------------------------------------------------------------------- /My_Learning/Day_66/ques: -------------------------------------------------------------------------------- 1 | Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". 2 | 3 | One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. 4 | 5 | Implement the MyCircularQueue class: 6 | 7 | MyCircularQueue(k) Initializes the object with the size of the queue to be k. 8 | int Front() Gets the front item from the queue. If the queue is empty, return -1. 9 | int Rear() Gets the last item from the queue. If the queue is empty, return -1. 10 | boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful. 11 | boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful. 12 | boolean isEmpty() Checks whether the circular queue is empty or not. 13 | boolean isFull() Checks whether the circular queue is full or not. 14 | -------------------------------------------------------------------------------- /My_Learning/Day_90/ValidateBST.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | 7 | def is_valid_bst(root): 8 | def is_valid(node, min_val, max_val): 9 | if not node: 10 | return True 11 | 12 | # Check if the current node's value is within the valid range 13 | if not (min_val < node.val < max_val): 14 | return False 15 | 16 | # Recursively check the left subtree and right subtree 17 | return (is_valid(node.left, min_val, node.val) and 18 | is_valid(node.right, node.val, max_val)) 19 | 20 | # Use a helper function to check the validity with initial range of (-inf, +inf) 21 | return is_valid(root, float('-inf'), float('inf')) 22 | 23 | # Test cases 24 | # Example 1: [2,1,3] 25 | root1 = TreeNode(2) 26 | root1.left = TreeNode(1) 27 | root1.right = TreeNode(3) 28 | print(is_valid_bst(root1)) # Output: True 29 | 30 | # Example 2: [5,1,4,null,null,3,6] 31 | root2 = TreeNode(5) 32 | root2.left = TreeNode(1) 33 | root2.right = TreeNode(4) 34 | root2.right.left = TreeNode(3) 35 | root2.right.right = TreeNode(6) 36 | print(is_valid_bst(root2)) # Output: False 37 | -------------------------------------------------------------------------------- /My_Learning/Day_20/ques: -------------------------------------------------------------------------------- 1 | A valid number can be split up into these components (in order): 2 | 3 | A decimal number or an integer. 4 | (Optional) An 'e' or 'E', followed by an integer. 5 | A decimal number can be split up into these components (in order): 6 | 7 | (Optional) A sign character (either '+' or '-'). 8 | One of the following formats: 9 | One or more digits, followed by a dot '.'. 10 | One or more digits, followed by a dot '.', followed by one or more digits. 11 | A dot '.', followed by one or more digits. 12 | An integer can be split up into these components (in order): 13 | 14 | (Optional) A sign character (either '+' or '-'). 15 | One or more digits. 16 | For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. 17 | 18 | Given a string s, return true if s is a valid number. 19 | 20 | Example 1: 21 | 22 | Input: s = "0" 23 | Output: true 24 | Example 2: 25 | 26 | Input: s = "e" 27 | Output: false 28 | Example 3: 29 | 30 | Input: s = "." 31 | Output: false 32 | 33 | Constraints: 34 | 35 | 1 <= s.length <= 20 36 | s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'. 37 | -------------------------------------------------------------------------------- /My_Learning/Day_78/ques: -------------------------------------------------------------------------------- 1 | You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of tokeni. 2 | 3 | Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token): 4 | 5 | Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score. 6 | Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score. 7 | Return the maximum possible score you can achieve after playing any number of tokens. 8 | 9 | Example 1: 10 | Input: tokens = [100], power = 50 11 | Output: 0 12 | Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100). 13 | 14 | Example 2: 15 | Input: tokens = [200,100], power = 150 16 | Output: 1 17 | Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1. 18 | There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1. 19 | 20 | Constraints: 21 | 22 | 0 <= tokens.length <= 1000 23 | 0 <= tokens[i], power < 104 24 | -------------------------------------------------------------------------------- /My_Learning/Day_82/RestoreIP.py: -------------------------------------------------------------------------------- 1 | def restoreIpAddresses(s): 2 | def is_valid_segment(segment): 3 | # Check if the segment is valid (between 0 and 255) 4 | if len(segment) > 1 and segment[0] == '0': # Avoid leading zeros 5 | return False 6 | num = int(segment) 7 | return 0 <= num <= 255 8 | 9 | def generate_ip_addresses(s, index, segments, current): 10 | # Base case: If we have formed 4 segments and used all characters in s 11 | if len(segments) == 4 and index == len(s): 12 | result.append(".".join(segments)) 13 | return 14 | 15 | # Try adding a segment of length 1, 2, or 3 characters 16 | for length in range(1, 4): 17 | if index + length > len(s): 18 | break # Out of bounds 19 | segment = s[index:index+length] 20 | if is_valid_segment(segment): 21 | segments.append(segment) 22 | generate_ip_addresses(s, index+length, segments, current) 23 | segments.pop() # Backtrack 24 | 25 | result = [] 26 | generate_ip_addresses(s, 0, [], "") 27 | return result 28 | 29 | # Test cases 30 | print(restoreIpAddresses("25525511135")) 31 | print(restoreIpAddresses("0000")) 32 | print(restoreIpAddresses("101023")) 33 | -------------------------------------------------------------------------------- /My_Learning/Day_36/ques: -------------------------------------------------------------------------------- 1 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: 2 | 3 | Every adjacent pair of words differs by a single letter. 4 | Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. 5 | sk == endWord 6 | Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. 7 | 8 | Example 1: 9 | 10 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 11 | Output: 5 12 | Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. 13 | Example 2: 14 | 15 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] 16 | Output: 0 17 | Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. 18 | 19 | Constraints: 20 | 21 | 1 <= beginWord.length <= 10 22 | endWord.length == beginWord.length 23 | 1 <= wordList.length <= 5000 24 | wordList[i].length == beginWord.length 25 | beginWord, endWord, and wordList[i] consist of lowercase English letters. 26 | beginWord != endWord 27 | All the words in wordList are unique. 28 | -------------------------------------------------------------------------------- /My_Learning/Day_43/ques: -------------------------------------------------------------------------------- 1 | A Bitset is a data structure that compactly stores bits. 2 | 3 | Implement the Bitset class: 4 | 5 | Bitset(int size) Initializes the Bitset with size bits, all of which are 0. 6 | void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs. 7 | void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs. 8 | void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa. 9 | boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise. 10 | boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise. 11 | int count() Returns the total number of bits in the Bitset which have value 1. 12 | String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset. 13 | 14 | Example 1: 15 | 16 | Input 17 | ["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"] 18 | [[5], [3], [1], [], [], [0], [], [], [0], [], []] 19 | Output 20 | [null, null, null, null, false, null, null, true, null, 2, "01010"] 21 | -------------------------------------------------------------------------------- /My_Learning/Day_87/ques: -------------------------------------------------------------------------------- 1 | Given two version numbers, version1 and version2, compare them. 2 | 3 | Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. 4 | 5 | To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. 6 | 7 | Return the following: 8 | 9 | If version1 < version2, return -1. 10 | If version1 > version2, return 1. 11 | Otherwise, return 0. 12 | 13 | Example 1: 14 | Input: version1 = "1.01", version2 = "1.001" 15 | Output: 0 16 | Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". 17 | 18 | Example 2: 19 | Input: version1 = "1.0", version2 = "1.0.0" 20 | Output: 0 21 | Explanation: version1 does not specify revision 2, which means it is treated as "0". 22 | -------------------------------------------------------------------------------- /My_Learning/Day_4/Function: -------------------------------------------------------------------------------- 1 | In Python, you can create functions using the **`def`** keyword. Here's an example of how you can define and use functions in Python: 2 | 3 | ```python 4 | 5 | # Function to add two numbers 6 | def add_numbers(a, b): 7 | result = a + b 8 | return result 9 | 10 | # Function to multiply two numbers 11 | def multiply_numbers(x, y): 12 | result = x * y 13 | return result 14 | 15 | # Function to greet a person 16 | def greet(name): 17 | return "Hello, " + name + "!" 18 | 19 | # Function to check if a number is even 20 | def is_even(number): 21 | return number % 2 == 0 22 | 23 | # Example usage of the functions 24 | sum_result = add_numbers(5, 3) 25 | print("Sum:", sum_result) 26 | 27 | product_result = multiply_numbers(4, 6) 28 | print("Product:", product_result) 29 | 30 | greeting = greet("Alice") 31 | print(greeting) 32 | 33 | number_to_check = 7 34 | if is_even(number_to_check): 35 | print(number_to_check, "is even.") 36 | else: 37 | print(number_to_check, "is odd.") 38 | 39 | ``` 40 | 41 | In this example, we defined four functions: 42 | 43 | 1. **`add_numbers`**: Takes two parameters and returns their sum. 44 | 2. **`multiply_numbers`**: Takes two parameters and returns their product. 45 | 3. **`greet`**: Takes a name as a parameter and returns a greeting. 46 | 4. **`is_even`**: Takes a number as a parameter and returns **`True`** if it's even, **`False`** otherwise. 47 | -------------------------------------------------------------------------------- /My_Learning/Day_58/Divide_integer.py: -------------------------------------------------------------------------------- 1 | def divide(dividend: int, divisor: int) -> int: 2 | # Handle edge cases 3 | if dividend == 0: 4 | return 0 5 | if divisor == 1: 6 | return dividend 7 | if divisor == -1: 8 | if dividend == -(2**31): 9 | return (2**31) - 1 10 | else: 11 | return -dividend 12 | 13 | # Determine the sign of the quotient 14 | negative = (dividend < 0) ^ (divisor < 0) 15 | 16 | # Make both dividend and divisor positive to simplify the algorithm 17 | dividend = abs(dividend) 18 | divisor = abs(divisor) 19 | 20 | quotient = 0 21 | while dividend >= divisor: 22 | temp = divisor 23 | power_of_two = 1 24 | while dividend >= (temp << 1): 25 | temp <<= 1 26 | power_of_two <<= 1 27 | dividend -= temp 28 | quotient += power_of_two 29 | 30 | if negative: 31 | quotient = -quotient 32 | 33 | # Handle overflow 34 | if quotient < -(2**31): 35 | return -(2**31) 36 | elif quotient > (2**31) - 1: 37 | return (2**31) - 1 38 | else: 39 | return quotient 40 | 41 | # Take user input for dividend and divisor 42 | dividend = int(input("Enter the dividend: ")) 43 | divisor = int(input("Enter the divisor: ")) 44 | 45 | # Perform division and print the result 46 | print("Quotient:", divide(dividend, divisor)) 47 | -------------------------------------------------------------------------------- /My_Learning/Day_9/Lamda: -------------------------------------------------------------------------------- 1 | In Python, **`lambda`** is a keyword that is used to create anonymous functions, also known as lambda functions. These functions are defined using the **`lambda`** keyword, followed by a list of input parameters, a colon (**`:`**), and an expression. 2 | 3 | Here is the general syntax of a lambda function: 4 | 5 | ```python 6 | pythonCopy code 7 | lambda arguments: expression 8 | 9 | ``` 10 | Here's an example of a simple lambda function that adds two numbers: 11 | 12 | ```python 13 | pythonCopy code 14 | add = lambda x, y: x + y 15 | result = add(3, 5) 16 | print(result) # Output: 8 17 | 18 | ``` 19 | In this example, the lambda function takes two arguments (**`x`** and **`y`**) and returns their sum. The **`lambda`** keyword is followed by the input parameters, a colon, and the expression that computes the result. 20 | 21 | Lambda functions are often used for short, simple operations and are frequently employed as arguments to higher-order functions (functions that take other functions as arguments). 22 | 23 | Here's an example using the **`map`** function with a lambda function to square each element in a list: 24 | 25 | ```python 26 | pythonCopy code 27 | numbers = [1, 2, 3, 4, 5] 28 | squared = list(map(lambda x: x**2, numbers)) 29 | print(squared) # Output: [1, 4, 9, 16, 25] 30 | 31 | ``` 32 | In this example, the **`lambda`** function squares each element in the **`numbers`** list, and the **`map`** function applies this lambda function to each element in the list 33 | -------------------------------------------------------------------------------- /My_Learning/Day_46/4Sum.py: -------------------------------------------------------------------------------- 1 | def fourSum(nums, target): 2 | nums.sort() 3 | quadruplets = [] 4 | n = len(nums) 5 | 6 | for i in range(n - 3): 7 | if i > 0 and nums[i] == nums[i - 1]: # Skip duplicates 8 | continue 9 | for j in range(i + 1, n - 2): 10 | if j > i + 1 and nums[j] == nums[j - 1]: # Skip duplicates 11 | continue 12 | left, right = j + 1, n - 1 13 | while left < right: 14 | current_sum = nums[i] + nums[j] + nums[left] + nums[right] 15 | if current_sum == target: 16 | quadruplets.append([nums[i], nums[j], nums[left], nums[right]]) 17 | while left < right and nums[left] == nums[left + 1]: # Skip duplicates 18 | left += 1 19 | while left < right and nums[right] == nums[right - 1]: # Skip duplicates 20 | right -= 1 21 | left += 1 22 | right -= 1 23 | elif current_sum < target: 24 | left += 1 25 | else: 26 | right -= 1 27 | return quadruplets 28 | 29 | # Test the function 30 | nums1 = [1, 0, -1, 0, -2, 2] 31 | target1 = 0 32 | print(fourSum(nums1, target1)) # Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] 33 | 34 | nums2 = [2, 2, 2, 2, 2] 35 | target2 = 8 36 | print(fourSum(nums2, target2)) # Output: [[2, 2, 2, 2]] 37 | -------------------------------------------------------------------------------- /My_Learning/Day_14/ques.txt: -------------------------------------------------------------------------------- 1 | You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. 2 | 3 | Merge nums1 and nums2 into a single array sorted in non-decreasing order. 4 | 5 | The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate 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 set to 0 and should be ignored. nums2 has a length of n. 6 | 7 | Example 1: 8 | 9 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 10 | Output: [1,2,2,3,5,6] 11 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. 12 | The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. 13 | Example 2: 14 | 15 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 16 | Output: [1] 17 | Explanation: The arrays we are merging are [1] and []. 18 | The result of the merge is [1]. 19 | Example 3: 20 | 21 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 22 | Output: [1] 23 | Explanation: The arrays we are merging are [] and [1]. 24 | The result of the merge is [1]. 25 | Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. 26 | 27 | Constraints: 28 | 29 | nums1.length == m + n 30 | nums2.length == n 31 | 0 <= m, n <= 200 32 | 1 <= m + n <= 200 33 | -109 <= nums1[i], nums2[j] <= 109 34 | -------------------------------------------------------------------------------- /My_Learning/Day_29/ques: -------------------------------------------------------------------------------- 1 | Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. 2 | 3 | Implement the LRUCache class: 4 | 5 | LRUCache(int capacity) Initialize the LRU cache with positive size capacity. 6 | int get(int key) Return the value of the key if the key exists, otherwise return -1. 7 | void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. 8 | The functions get and put must each run in O(1) average time complexity. 9 | 10 | Example 1: 11 | 12 | Input 13 | ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] 14 | [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] 15 | Output 16 | [null, null, null, 1, null, -1, null, -1, 3, 4] 17 | 18 | Explanation 19 | LRUCache lRUCache = new LRUCache(2); 20 | lRUCache.put(1, 1); // cache is {1=1} 21 | lRUCache.put(2, 2); // cache is {1=1, 2=2} 22 | lRUCache.get(1); // return 1 23 | lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} 24 | lRUCache.get(2); // returns -1 (not found) 25 | lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} 26 | lRUCache.get(1); // return -1 (not found) 27 | lRUCache.get(3); // return 3 28 | lRUCache.get(4); // return 4 29 | 30 | Constraints: 31 | 32 | 1 <= capacity <= 3000 33 | 0 <= key <= 104 34 | 0 <= value <= 105 35 | At most 2 * 105 calls will be made to get and put. 36 | -------------------------------------------------------------------------------- /My_Learning/Day_3/Arrays: -------------------------------------------------------------------------------- 1 | 2 | In Python, an array can be represented using a list, which is a built-in data structure. Lists are flexible and can store elements of different data types. Here's a brief example of how you can work with arrays using lists in Python: 3 | 4 | python 5 | Copy code 6 | # Creating an array (list) 7 | my_array = [1, 2, 3, 4, 5] 8 | 9 | # Accessing elements in the array 10 | print("Array:", my_array) 11 | print("First element:", my_array[0]) 12 | print("Second element:", my_array[1]) 13 | 14 | # Modifying elements in the array 15 | my_array[2] = 10 16 | print("Modified array:", my_array) 17 | 18 | # Adding elements to the array 19 | my_array.append(6) 20 | print("Array after appending 6:", my_array) 21 | 22 | # Removing elements from the array 23 | my_array.remove(4) 24 | print("Array after removing 4:", my_array) 25 | 26 | # Length of the array 27 | array_length = len(my_array) 28 | print("Length of the array:", array_length) 29 | In this example, my_array is a list containing integers. You can access elements using indexing, modify elements, append new elements, remove elements, and determine the length of the array using the len function. 30 | 31 | If you want to take user input for an array, you can use the input function and then convert the input into a list of integers. Here's a simple example: 32 | 33 | python 34 | Copy code 35 | # Take user input for an array 36 | user_input = input("Enter numbers separated by spaces: ") 37 | user_array = [int(x) for x in user_input.split()] 38 | 39 | print("User's array:", user_array) 40 | -------------------------------------------------------------------------------- /My_Learning/Day_52/ques: -------------------------------------------------------------------------------- 1 | You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time. 2 | 3 | ​Return the minimum number of intervals required to complete all tasks. 4 | 5 | Example 1: 6 | 7 | Input: tasks = ["A","A","A","B","B","B"], n = 2 8 | 9 | Output: 8 10 | 11 | Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. 12 | 13 | After completing task A, you must wait two cycles before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th cycle, you can do A again as 2 intervals have passed. 14 | 15 | Example 2: 16 | 17 | Input: tasks = ["A","C","A","B","D","B"], n = 1 18 | 19 | Output: 6 20 | 21 | Explanation: A possible sequence is: A -> B -> C -> D -> A -> B. 22 | 23 | With a cooling interval of 1, you can repeat a task after just one other task. 24 | 25 | Example 3: 26 | 27 | Input: tasks = ["A","A","A", "B","B","B"], n = 3 28 | 29 | Output: 10 30 | 31 | Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B. 32 | 33 | There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks. 34 | 35 | Constraints: 36 | 37 | 1 <= tasks.length <= 104 38 | tasks[i] is an uppercase English letter. 39 | 0 <= n <= 100 40 | -------------------------------------------------------------------------------- /My_Learning/Day_74/ques: -------------------------------------------------------------------------------- 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 | Constraints: 40 | 41 | 1 <= s.length <= 15 42 | s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). 43 | It is guaranteed that s is a valid roman numeral in the range [1, 3999]. 44 | -------------------------------------------------------------------------------- /My_Learning/Day_41/4Sum.py: -------------------------------------------------------------------------------- 1 | def fourSum(nums, target): 2 | nums.sort() 3 | result = [] 4 | 5 | def threeSum(start, target): 6 | triplets = [] 7 | for i in range(start, len(nums) - 2): 8 | if i > start and nums[i] == nums[i - 1]: 9 | continue 10 | left, right = i + 1, len(nums) - 1 11 | while left < right: 12 | total = nums[i] + nums[left] + nums[right] 13 | if total == target: 14 | triplets.append([nums[i], nums[left], nums[right]]) 15 | while left < right and nums[left] == nums[left + 1]: 16 | left += 1 17 | while left < right and nums[right] == nums[right - 1]: 18 | right -= 1 19 | left += 1 20 | right -= 1 21 | elif total < target: 22 | left += 1 23 | else: 24 | right -= 1 25 | return triplets 26 | 27 | for i in range(len(nums) - 3): 28 | if i > 0 and nums[i] == nums[i - 1]: 29 | continue 30 | triplets = threeSum(i + 1, target - nums[i]) 31 | for triplet in triplets: 32 | result.append([nums[i]] + triplet) 33 | 34 | return result 35 | 36 | # Example usage: 37 | nums1 = [1, 0, -1, 0, -2, 2] 38 | target1 = 0 39 | nums2 = [2, 2, 2, 2, 2] 40 | target2 = 8 41 | 42 | print("Output for nums1 and target1:", fourSum(nums1, target1)) 43 | print("Output for nums2 and target2:", fourSum(nums2, target2)) 44 | -------------------------------------------------------------------------------- /My_Learning/Day_57/AccountsMerge.py: -------------------------------------------------------------------------------- 1 | def accountsMerge(accounts): 2 | # Build the graph 3 | graph = {} 4 | for account in accounts: 5 | name = account[0] 6 | for email in account[1:]: 7 | if email not in graph: 8 | graph[email] = set() 9 | graph[email].add(account[1]) # Add the first email as a representative 10 | 11 | graph[account[1]].add(email) # Add other emails 12 | 13 | # DFS function to traverse the graph 14 | def dfs(email, visited, component): 15 | visited.add(email) 16 | component.append(email) 17 | for neighbor in graph[email]: 18 | if neighbor not in visited: 19 | dfs(neighbor, visited, component) 20 | 21 | merged_accounts = [] 22 | visited = set() 23 | for email in graph: 24 | if email not in visited: 25 | component = [] 26 | dfs(email, visited, component) 27 | merged_accounts.append([accounts[0][0]] + sorted(component)) 28 | 29 | return merged_accounts 30 | 31 | # Example usage: 32 | accounts1 = [["John","johnsmith@mail.com","john_newyork@mail.com"], 33 | ["John","johnsmith@mail.com","john00@mail.com"], 34 | ["Mary","mary@mail.com"], 35 | ["John","johnnybravo@mail.com"]] 36 | print(accountsMerge(accounts1)) 37 | 38 | accounts2 = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"], 39 | ["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"], 40 | ["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"], 41 | ["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m 42 | -------------------------------------------------------------------------------- /My_Learning/Day_53/AccountsMerge.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | def accountsMerge(accounts): 4 | # Build the graph 5 | graph = defaultdict(list) 6 | email_to_name = {} 7 | for account in accounts: 8 | name = account[0] 9 | emails = account[1:] 10 | for email in emails: 11 | graph[emails[0]].append(email) 12 | graph[email].append(emails[0]) 13 | email_to_name[email] = name 14 | 15 | # Perform DFS to traverse connected components 16 | def dfs(email, component): 17 | component.add(email) 18 | for neighbor in graph[email]: 19 | if neighbor not in component: 20 | dfs(neighbor, component) 21 | 22 | # Perform DFS for each email 23 | visited = set() 24 | result = [] 25 | for email in graph: 26 | if email not in visited: 27 | component = set() 28 | dfs(email, component) 29 | result.append([email_to_name[email]] + sorted(component)) 30 | visited.update(component) 31 | 32 | return result 33 | 34 | # Test cases 35 | accounts1 = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] 36 | accounts2 = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]] 37 | 38 | print(accountsMerge(accounts1)) 39 | print(accountsMerge(accounts2)) 40 | -------------------------------------------------------------------------------- /My_Learning/Day_48/ReorderList.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def reorderList(head): 7 | if not head or not head.next: 8 | return head 9 | 10 | # Step 1: Find the middle of the linked list 11 | slow = fast = head 12 | while fast.next and fast.next.next: 13 | slow = slow.next 14 | fast = fast.next.next 15 | 16 | # Step 2: Reverse the second half of the linked list 17 | prev = None 18 | curr = slow.next 19 | while curr: 20 | temp = curr.next 21 | curr.next = prev 22 | prev = curr 23 | curr = temp 24 | slow.next = None 25 | 26 | # Step 3: Merge the first half and the reversed second half alternatively 27 | first = head 28 | second = prev 29 | while second: 30 | temp1 = first.next 31 | temp2 = second.next 32 | first.next = second 33 | second.next = temp1 34 | first = temp1 35 | second = temp2 36 | 37 | return head 38 | 39 | # Helper function to print the linked list 40 | def printLinkedList(head): 41 | result = [] 42 | while head: 43 | result.append(head.val) 44 | head = head.next 45 | print(" -> ".join(map(str, result))) 46 | 47 | # Test the function 48 | head = ListNode(1) 49 | head.next = ListNode(2) 50 | head.next.next = ListNode(3) 51 | head.next.next.next = ListNode(4) 52 | head.next.next.next.next = ListNode(5) 53 | print("Original linked list:") 54 | printLinkedList(head) 55 | reorderList(head) 56 | print("Reordered linked list:") 57 | printLinkedList(head) 58 | -------------------------------------------------------------------------------- /My_Learning/Day_24/mergeKSortedList.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def mergeKLists(lists): 7 | nodes = [] 8 | for linked_list in lists: 9 | while linked_list: 10 | nodes.append(linked_list.val) 11 | linked_list = linked_list.next 12 | nodes.sort() 13 | 14 | dummy = ListNode() 15 | current = dummy 16 | for node_val in nodes: 17 | current.next = ListNode(node_val) 18 | current = current.next 19 | 20 | return dummy.next 21 | 22 | # Function to print the linked list 23 | def printLinkedList(head): 24 | current = head 25 | while current: 26 | print(current.val, end=" ") 27 | current = current.next 28 | print() 29 | 30 | # Function to create a linked list from a list of values 31 | def createLinkedList(values): 32 | if not values: 33 | return None 34 | head = ListNode(values[0]) 35 | current = head 36 | for val in values[1:]: 37 | current.next = ListNode(val) 38 | current = current.next 39 | return head 40 | 41 | # Take user input for the number of lists 42 | num_lists = int(input("Enter the number of linked lists: ")) 43 | 44 | # Take user input for each linked list 45 | lists = [] 46 | for i in range(num_lists): 47 | input_str = input(f"Enter the space-separated values for linked list {i + 1}: ") 48 | values = list(map(int, input_str.split())) 49 | linked_list = createLinkedList(values) 50 | lists.append(linked_list) 51 | 52 | # Merge the linked lists 53 | merged_list = mergeKLists(lists) 54 | 55 | # Print the merged linked list 56 | print("Merged linked list:") 57 | printLinkedList(merged_list) 58 | -------------------------------------------------------------------------------- /My_Learning/Day_66/CircularQueue.py: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | 3 | def __init__(self, k: int): 4 | self.size = k 5 | self.queue = [None] * k 6 | self.front = self.rear = -1 7 | 8 | def enQueue(self, value: int) -> bool: 9 | if self.isFull(): 10 | return False 11 | if self.isEmpty(): 12 | self.front = 0 13 | self.rear = (self.rear + 1) % self.size 14 | self.queue[self.rear] = value 15 | return True 16 | 17 | def deQueue(self) -> bool: 18 | if self.isEmpty(): 19 | return False 20 | if self.front == self.rear: 21 | self.front = self.rear = -1 22 | else: 23 | self.front = (self.front + 1) % self.size 24 | return True 25 | 26 | def Front(self) -> int: 27 | if self.isEmpty(): 28 | return -1 29 | return self.queue[self.front] 30 | 31 | def Rear(self) -> int: 32 | if self.isEmpty(): 33 | return -1 34 | return self.queue[self.rear] 35 | 36 | def isEmpty(self) -> bool: 37 | return self.front == -1 38 | 39 | def isFull(self) -> bool: 40 | return (self.rear + 1) % self.size == self.front 41 | 42 | 43 | # Example usage: 44 | myCircularQueue = MyCircularQueue(3) 45 | print(myCircularQueue.enQueue(1)) # Output: True 46 | print(myCircularQueue.enQueue(2)) # Output: True 47 | print(myCircularQueue.enQueue(3)) # Output: True 48 | print(myCircularQueue.enQueue(4)) # Output: False 49 | print(myCircularQueue.Rear()) # Output: 3 50 | print(myCircularQueue.isFull()) # Output: True 51 | print(myCircularQueue.deQueue()) # Output: True 52 | print(myCircularQueue.enQueue(4)) # Output: True 53 | print(myCircularQueue.Rear()) # Output: 4 54 | -------------------------------------------------------------------------------- /My_Learning/Day_13/ques: -------------------------------------------------------------------------------- 1 | Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. 2 | 3 | Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things: 4 | 5 | Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. 6 | Return k. 7 | Custom Judge: 8 | 9 | The judge will test your solution with the following code: 10 | 11 | int[] nums = [...]; // Input array 12 | int[] expectedNums = [...]; // The expected answer with correct length 13 | 14 | int k = removeDuplicates(nums); // Calls your implementation 15 | 16 | assert k == expectedNums.length; 17 | for (int i = 0; i < k; i++) { 18 | assert nums[i] == expectedNums[i]; 19 | } 20 | If all assertions pass, then your solution will be accepted. 21 | 22 | 23 | 24 | Example 1: 25 | 26 | Input: nums = [1,1,2] 27 | Output: 2, nums = [1,2,_] 28 | Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. 29 | It does not matter what you leave beyond the returned k (hence they are underscores). 30 | Example 2: 31 | 32 | Input: nums = [0,0,1,1,1,2,2,3,3,4] 33 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 34 | Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. 35 | It does not matter what you leave beyond the returned k (hence they are underscores). 36 | 37 | 38 | Constraints: 39 | 40 | 1 <= nums.length <= 3 * 104 41 | -100 <= nums[i] <= 100 42 | nums is sorted in non-decreasing order. 43 | -------------------------------------------------------------------------------- /My_Learning/Day_21/ques: -------------------------------------------------------------------------------- 1 | We can scramble a string s to get a string t using the following algorithm: 2 | 3 | If the length of the string is 1, stop. 4 | If the length of the string is > 1, do the following: 5 | Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y. 6 | Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x. 7 | Apply step 1 recursively on each of the two substrings x and y. 8 | Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false. 9 | 10 | Example 1: 11 | 12 | Input: s1 = "great", s2 = "rgeat" 13 | Output: true 14 | Explanation: One possible scenario applied on s1 is: 15 | "great" --> "gr/eat" // divide at random index. 16 | "gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order. 17 | "gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them. 18 | "g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order. 19 | "r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t". 20 | "r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order. 21 | The algorithm stops now, and the result string is "rgeat" which is s2. 22 | As one possible scenario led s1 to be scrambled to s2, we return true. 23 | Example 2: 24 | 25 | Input: s1 = "abcde", s2 = "caebd" 26 | Output: false 27 | Example 3: 28 | 29 | Input: s1 = "a", s2 = "a" 30 | Output: true 31 | 32 | Constraints: 33 | 34 | s1.length == s2.length 35 | 1 <= s1.length <= 30 36 | s1 and s2 consist of lowercase English letters. 37 | -------------------------------------------------------------------------------- /My_Learning/Day_2/basic: -------------------------------------------------------------------------------- 1 | # Variables: 2 | In Python, you can assign values to variables using the equal sign (=). Variables are dynamically typed, meaning you don't have to declare their type explicitly. 3 | 4 | x = 5 # x is an integer 5 | y = 3.14 # y is a floating-point number 6 | name = "John" # name is a string 7 | 8 | # Data Types: 9 | 10 | 1. Numeric Types: 11 | int: Integer type (e.g., 5, -3). 12 | float: Floating-point type (e.g., 3.14, -0.5). 13 | 14 | 2. Text Type: 15 | str: String type (e.g., "Hello", 'Python'). 16 | 17 | 3. Boolean Type: 18 | bool: Boolean type (True or False). 19 | 20 | 4. Sequence Types: 21 | list: Ordered and mutable collection. 22 | tuple: Ordered and immutable collection. 23 | range: Represents a sequence of numbers. 24 | 25 | 5. Set Types: 26 | set: Unordered and mutable collection of unique elements. 27 | frozenset: Unordered and immutable collection of unique elements. 28 | 29 | 6. Mapping Type: 30 | dict: Unordered collection of key-value pairs. 31 | 32 | num = 42 # int 33 | pi = 3.14159 # float 34 | greeting = "Hello" # str 35 | is_python_fun = True # bool 36 | 37 | my_list = [1, 2, 3] # list 38 | my_tuple = (4, 5, 6) # tuple 39 | my_set = {1, 2, 3} # set 40 | my_dict = {'a': 10, 'b': 20} # dict 41 | 42 | # Basic Operations: 43 | 44 | 1. Arithmetic Operations: 45 | 46 | addition = 5 + 3 47 | subtraction = 7 - 2 48 | multiplication = 4 * 6 49 | division = 10 / 2 50 | 51 | 2. String Operations: 52 | 53 | greeting = "Hello" 54 | name = "John" 55 | full_greeting = greeting + " " + name 56 | 57 | # Control Flow: 58 | # Conditional Statements: 59 | 60 | x = 10 61 | if x > 0: 62 | print("Positive") 63 | elif x == 0: 64 | print("Zero") 65 | else: 66 | print("Negative") 67 | 68 | # Loops: 69 | 70 | 1. for i in range(5): 71 | print(i) 72 | 73 | 2. while x > 0: 74 | print(x) 75 | x -= 1 76 | -------------------------------------------------------------------------------- /My_Learning/Day_96/HashMap.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, key, value): 3 | self.key = key 4 | self.value = value 5 | self.next = None 6 | 7 | class MyHashMap: 8 | def __init__(self): 9 | self.size = 1000 10 | self.buckets = [None] * self.size 11 | 12 | def put(self, key: int, value: int) -> None: 13 | index = key % self.size 14 | if self.buckets[index] is None: 15 | self.buckets[index] = Node(key, value) 16 | else: 17 | current = self.buckets[index] 18 | while True: 19 | if current.key == key: 20 | current.value = value 21 | return 22 | if current.next is None: 23 | break 24 | current = current.next 25 | current.next = Node(key, value) 26 | 27 | def get(self, key: int) -> int: 28 | index = key % self.size 29 | current = self.buckets[index] 30 | while current: 31 | if current.key == key: 32 | return current.value 33 | current = current.next 34 | return -1 35 | 36 | def remove(self, key: int) -> None: 37 | index = key % self.size 38 | current = prev = self.buckets[index] 39 | if not current: 40 | return 41 | if current.key == key: 42 | self.buckets[index] = current.next 43 | else: 44 | current = current.next 45 | while current: 46 | if current.key == key: 47 | prev.next = current.next 48 | return 49 | prev, current = current, current.next 50 | 51 | # Example usage 52 | obj = MyHashMap() 53 | obj.put(1, 1) 54 | obj.put(2, 2) 55 | print(obj.get(1)) # Output: 1 56 | print(obj.get(3)) # Output: -1 57 | obj.put(2, 1) 58 | print(obj.get(2)) # Output: 1 59 | obj.remove(2) 60 | print(obj.get(2)) # Output: -1 61 | -------------------------------------------------------------------------------- /My_Learning/Day_63/RemoveNodes.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def removeNodesWithGreaterValues(head): 7 | if not head: 8 | return None 9 | 10 | # Dummy node to handle cases where the head itself needs to be removed 11 | dummy = ListNode(0) 12 | dummy.next = head 13 | 14 | max_val = float('-inf') 15 | current = head 16 | prev = dummy 17 | 18 | while current: 19 | if current.val < max_val: 20 | # Remove the current node 21 | prev.next = current.next 22 | else: 23 | # Update the maximum value encountered so far 24 | max_val = max(max_val, current.val) 25 | prev = current 26 | current = current.next 27 | 28 | return dummy.next 29 | 30 | # Function to print the linked list 31 | def printLinkedList(head): 32 | current = head 33 | while current: 34 | print(current.val, end=" -> ") 35 | current = current.next 36 | print("None") 37 | 38 | # Example usage: 39 | # Create the linked list: 5 -> 2 -> 13 -> 3 -> 8 40 | head1 = ListNode(5) 41 | head1.next = ListNode(2) 42 | head1.next.next = ListNode(13) 43 | head1.next.next.next = ListNode(3) 44 | head1.next.next.next.next = ListNode(8) 45 | 46 | print("Original linked list:") 47 | printLinkedList(head1) 48 | 49 | # Remove nodes with greater values 50 | new_head1 = removeNodesWithGreaterValues(head1) 51 | 52 | print("\nModified linked list:") 53 | printLinkedList(new_head1) 54 | 55 | 56 | # Create the linked list: 1 -> 1 -> 1 -> 1 57 | head2 = ListNode(1) 58 | head2.next = ListNode(1) 59 | head2.next.next = ListNode(1) 60 | head2.next.next.next = ListNode(1) 61 | 62 | print("\nOriginal linked list:") 63 | printLinkedList(head2) 64 | 65 | # Remove nodes with greater values 66 | new_head2 = removeNodesWithGreaterValues(head2) 67 | 68 | print("\nModified linked list:") 69 | printLinkedList(new_head2) 70 | -------------------------------------------------------------------------------- /My_Learning/Day_64/CountGoodNumbers.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def removeNodesWithGreaterValues(head): 7 | if not head: 8 | return None 9 | 10 | # Dummy node to handle cases where the head itself needs to be removed 11 | dummy = ListNode(0) 12 | dummy.next = head 13 | 14 | max_val = float('-inf') 15 | current = head 16 | prev = dummy 17 | 18 | while current: 19 | if current.val < max_val: 20 | # Remove the current node 21 | prev.next = current.next 22 | else: 23 | # Update the maximum value encountered so far 24 | max_val = max(max_val, current.val) 25 | prev = current 26 | current = current.next 27 | 28 | return dummy.next 29 | 30 | # Function to print the linked list 31 | def printLinkedList(head): 32 | current = head 33 | while current: 34 | print(current.val, end=" -> ") 35 | current = current.next 36 | print("None") 37 | 38 | # Example usage: 39 | # Create the linked list: 5 -> 2 -> 13 -> 3 -> 8 40 | head1 = ListNode(5) 41 | head1.next = ListNode(2) 42 | head1.next.next = ListNode(13) 43 | head1.next.next.next = ListNode(3) 44 | head1.next.next.next.next = ListNode(8) 45 | 46 | print("Original linked list:") 47 | printLinkedList(head1) 48 | 49 | # Remove nodes with greater values 50 | new_head1 = removeNodesWithGreaterValues(head1) 51 | 52 | print("\nModified linked list:") 53 | printLinkedList(new_head1) 54 | 55 | 56 | # Create the linked list: 1 -> 1 -> 1 -> 1 57 | head2 = ListNode(1) 58 | head2.next = ListNode(1) 59 | head2.next.next = ListNode(1) 60 | head2.next.next.next = ListNode(1) 61 | 62 | print("\nOriginal linked list:") 63 | printLinkedList(head2) 64 | 65 | # Remove nodes with greater values 66 | new_head2 = removeNodesWithGreaterValues(head2) 67 | 68 | print("\nModified linked list:") 69 | printLinkedList(new_head2) 70 | -------------------------------------------------------------------------------- /My_Learning/Day_75/LinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, val=0, prev=None, next=None, child=None): 3 | self.val = val 4 | self.prev = prev 5 | self.next = next 6 | self.child = child 7 | 8 | def flatten(head: 'Node') -> 'Node': 9 | if not head: 10 | return None 11 | 12 | def flatten_util(curr): 13 | while curr: 14 | if curr.child: 15 | child_head = curr.child 16 | child_tail = flatten_util(child_head) 17 | child_tail.next = curr.next 18 | if curr.next: 19 | curr.next.prev = child_tail 20 | curr.next = child_head 21 | child_head.prev = curr 22 | curr.child = None 23 | curr = child_tail 24 | if not curr.next: 25 | break 26 | curr = curr.next 27 | return curr 28 | 29 | flatten_util(head) 30 | return head 31 | 32 | # Example usage: 33 | # Construct the multilevel doubly linked list 34 | head = Node(1) 35 | head.next = Node(2) 36 | head.next.prev = head 37 | head.next.next = Node(3) 38 | head.next.next.prev = head.next 39 | head.next.next.next = Node(4) 40 | head.next.next.next.prev = head.next.next 41 | head.next.next.next.next = Node(5) 42 | head.next.next.next.next.prev = head.next.next.next 43 | head.next.child = Node(7) 44 | head.next.child.next = Node(8) 45 | head.next.child.next.prev = head.next.child 46 | head.next.child.next.next = Node(11) 47 | head.next.child.next.next.prev = head.next.child.next 48 | head.next.next.next.child = Node(9) 49 | head.next.next.next.child.next = Node(10) 50 | head.next.next.next.child.next.prev = head.next.next.next.child 51 | head.next.next.next.child.child = Node(12) 52 | 53 | # Flatten the multilevel doubly linked list 54 | flattened_head = flatten(head) 55 | 56 | # Print the flattened list 57 | current = flattened_head 58 | while current: 59 | print(current.val, end=" -> ") 60 | current = current.next 61 | -------------------------------------------------------------------------------- /My_Learning/Day_94/Sorted List.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class ListNode: 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | def mergeKLists(lists): 9 | # Create a min-heap to store (value, node) pairs 10 | min_heap = [] 11 | 12 | # Add the head of each linked list to the min-heap 13 | for head in lists: 14 | if head: 15 | heapq.heappush(min_heap, (head.val, head)) 16 | 17 | # Create a dummy node to build the merged list 18 | dummy = ListNode() 19 | current = dummy 20 | 21 | # Merge using the min-heap 22 | while min_heap: 23 | # Pop the node with the smallest value from the heap 24 | val, node = heapq.heappop(min_heap) 25 | 26 | # Append this node to the merged list 27 | current.next = node 28 | current = current.next 29 | 30 | # Push the next node of the popped node to the heap 31 | if node.next: 32 | heapq.heappush(min_heap, (node.next.val, node.next)) 33 | 34 | # Return the merged list starting from dummy.next 35 | return dummy.next 36 | 37 | # Helper function to create a linked list from a list of values 38 | def createLinkedList(values): 39 | if not values: 40 | return None 41 | head = ListNode(values[0]) 42 | current = head 43 | for value in values[1:]: 44 | current.next = ListNode(value) 45 | current = current.next 46 | return head 47 | 48 | # Helper function to convert a linked list to a list 49 | def linkedListToList(head): 50 | result = [] 51 | current = head 52 | while current: 53 | result.append(current.val) 54 | current = current.next 55 | return result 56 | 57 | # Test the mergeKLists function 58 | lists = [ 59 | createLinkedList([1,4,5]), 60 | createLinkedList([1,3,4]), 61 | createLinkedList([2,6]) 62 | ] 63 | merged_list = mergeKLists(lists) 64 | print(linkedListToList(merged_list)) # Output: [1,1,2,3,4,4,5,6] 65 | -------------------------------------------------------------------------------- /My_Learning/Day_80/Linkedlist.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | 7 | def flatten(root): 8 | if not root: 9 | return 10 | 11 | # Recursive function to flatten the subtree rooted at 'node' 12 | def flattenSubtree(node): 13 | if not node: 14 | return None 15 | 16 | # Flatten the left and right subtrees recursively 17 | left_end = flattenSubtree(node.left) 18 | right_end = flattenSubtree(node.right) 19 | 20 | # Save the original right subtree 21 | right_subtree = node.right 22 | 23 | # Make the left subtree the new right subtree 24 | node.right = node.left 25 | node.left = None 26 | 27 | # Attach the original right subtree to the end of the current flattened subtree 28 | if left_end: 29 | left_end.right = right_subtree 30 | else: 31 | # If no left subtree was flattened, set right_end to node (current root) 32 | right_end = node 33 | 34 | return right_end 35 | 36 | # Start flattening the tree from the root 37 | flattenSubtree(root) 38 | 39 | # Helper function to perform pre-order traversal and collect values 40 | def preorderTraversal(root): 41 | result = [] 42 | stack = [root] 43 | while stack: 44 | node = stack.pop() 45 | if node: 46 | result.append(node.val) 47 | stack.append(node.right) 48 | stack.append(node.left) 49 | return result 50 | 51 | # Example usage: 52 | # Construct the example tree [1,2,5,3,4,null,6] 53 | root = TreeNode(1) 54 | root.left = TreeNode(2) 55 | root.right = TreeNode(5) 56 | root.left.left = TreeNode(3) 57 | root.left.right = TreeNode(4) 58 | root.right.right = TreeNode(6) 59 | 60 | print("Original tree (pre-order traversal):", preorderTraversal(root)) 61 | 62 | flatten(root) 63 | 64 | print("Flattened tree (pre-order traversal):", preorderTraversal(root)) 65 | -------------------------------------------------------------------------------- /My_Learning/Day_5/List: -------------------------------------------------------------------------------- 1 | In Python, a list is a built-in data structure that represents an ordered and mutable collection of elements. Lists are versatile and widely used for storing and manipulating data. Here's an overview of lists in Python: 2 | 3 | ### **List Basics:** 4 | 5 | - **Definition:** An ordered collection of elements enclosed in square brackets **`[]`**. 6 | - **Example:** 7 | 8 | ```python 9 | 10 | my_list = [1, 2, 3, 'four'] 11 | 12 | ``` 13 | 14 | 15 | ### **Common Operations:** 16 | 17 | 1. **Access Elements:** 18 | - Elements in a list are accessed by index, starting from 0. 19 | 20 | ```python 21 | 22 | print(my_list[0]) # Output: 1 23 | 24 | ``` 25 | 26 | 2. **Modify Elements:** 27 | - Lists are mutable, meaning you can change their elements. 28 | 29 | ```python 30 | 31 | my_list[1] = 'two' 32 | print(my_list) # Output: [1, 'two', 3, 'four'] 33 | 34 | ``` 35 | 36 | 3. **Add Elements:** 37 | - You can append elements to the end of the list. 38 | 39 | ```python 40 | 41 | my_list.append(5) 42 | print(my_list) # Output: [1, 'two', 3, 'four', 5] 43 | 44 | ``` 45 | 46 | 4. **Remove Elements:** 47 | - Elements can be removed by value or index. 48 | 49 | ```python 50 | 51 | my_list.remove('two') 52 | print(my_list) # Output: [1, 3, 'four', 5] 53 | 54 | ``` 55 | 56 | 5. **Slicing:** 57 | - Extracting a portion of the list (a sublist). 58 | 59 | ```python 60 | 61 | sublist = my_list[1:3] 62 | print(sublist) # Output: [3, 'four'] 63 | 64 | ``` 65 | 66 | 6. **Length of a List:** 67 | - Get the number of elements in a list. 68 | 69 | ```python 70 | 71 | length = len(my_list) 72 | print(length) # Output: 4 73 | 74 | ``` 75 | 76 | 7. **Concatenation:** 77 | - Combining two or more lists. 78 | 79 | ```python 80 | 81 | new_list = my_list + [6, 7] 82 | print(new_list) # Output: [1, 3, 'four', 5, 6, 7] 83 | 84 | ``` 85 | 86 | 8. **Nested Lists:** 87 | - Lists can contain other lists. 88 | 89 | ```python 90 | 91 | nested_list = [1, [2, 3], 'four'] 92 | print(nested_list[1]) # Output: [2, 3] 93 | 94 | ``` 95 | 96 | 97 | Lists are flexible and can hold elements of different data types. They are commonly used in various programming scenarios due to their versatility. 98 | -------------------------------------------------------------------------------- /My_Learning/Day_7/Tuples: -------------------------------------------------------------------------------- 1 | In Python, a tuple is a collection of ordered and immutable elements. Here are some key characteristics and operations related to tuples: 2 | 3 | 1. **Creation:** 4 | - Tuples are created by placing a sequence of values separated by commas inside parentheses **`()`**. 5 | 6 | ```python 7 | 8 | my_tuple = (1, 2, 3, 'hello') 9 | 10 | ``` 11 | 12 | 2. **Accessing Elements:** 13 | - Elements of a tuple are accessed using indexing, similar to lists. 14 | 15 | ```python 16 | 17 | print(my_tuple[0]) # Output: 1 18 | 19 | ``` 20 | 21 | 3. **Immutable:** 22 | - Tuples are immutable, meaning once they are created, their elements cannot be changed or modified. 23 | 24 | ```python 25 | 26 | # This will raise an error 27 | my_tuple[0] = 5 28 | 29 | ``` 30 | 31 | 4. **Length:** 32 | - You can find the length (number of elements) of a tuple using the **`len()`** function. 33 | 34 | ```python 35 | 36 | print(len(my_tuple)) 37 | 38 | ``` 39 | 40 | 5. **Slicing:** 41 | - You can use slicing to extract a portion of the tuple. 42 | 43 | ```python 44 | 45 | subset_tuple = my_tuple[1:3] 46 | 47 | ``` 48 | 49 | 6. **Concatenation:** 50 | - Tuples can be concatenated using the **`+`** operator. 51 | 52 | ```python 53 | 54 | new_tuple = my_tuple + (4, 5, 6) 55 | 56 | ``` 57 | 58 | 7. **Repetition:** 59 | - Tuples can be repeated using the **``** operator. 60 | 61 | ```python 62 | 63 | repeated_tuple = my_tuple * 2 64 | 65 | ``` 66 | 67 | 8. **Deleting:** 68 | - You cannot delete elements of a tuple, but you can delete the entire tuple. 69 | 70 | ```python 71 | 72 | del my_tuple 73 | 74 | ``` 75 | 76 | 9. **Nested Tuples:** 77 | - Tuples can contain other tuples, creating nested structures. 78 | 79 | ```python 80 | 81 | nested_tuple = (1, (2, 3), 'hello') 82 | 83 | ``` 84 | 85 | 86 | Tuples are often used when you want to create an immutable sequence of elements. They are commonly used in scenarios where the data should not be modified after creation. 87 | -------------------------------------------------------------------------------- /My_Learning/Day_67/CircularDequeue.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, prev=None, next=None): 3 | self.val = val 4 | self.prev = prev 5 | self.next = next 6 | 7 | class MyCircularDeque: 8 | 9 | def __init__(self, k: int): 10 | self.size = 0 11 | self.capacity = k 12 | self.head = ListNode() 13 | self.tail = ListNode() 14 | self.head.next = self.tail 15 | self.tail.prev = self.head 16 | 17 | def insertFront(self, value: int) -> bool: 18 | if self.isFull(): 19 | return False 20 | new_node = ListNode(value, self.head, self.head.next) 21 | self.head.next.prev = new_node 22 | self.head.next = new_node 23 | self.size += 1 24 | return True 25 | 26 | def insertLast(self, value: int) -> bool: 27 | if self.isFull(): 28 | return False 29 | new_node = ListNode(value, self.tail.prev, self.tail) 30 | self.tail.prev.next = new_node 31 | self.tail.prev = new_node 32 | self.size += 1 33 | return True 34 | 35 | def deleteFront(self) -> bool: 36 | if self.isEmpty(): 37 | return False 38 | self.head.next.next.prev = self.head 39 | self.head.next = self.head.next.next 40 | self.size -= 1 41 | return True 42 | 43 | def deleteLast(self) -> bool: 44 | if self.isEmpty(): 45 | return False 46 | self.tail.prev.prev.next = self.tail 47 | self.tail.prev = self.tail.prev.prev 48 | self.size -= 1 49 | return True 50 | 51 | def getFront(self) -> int: 52 | return self.head.next.val if self.size > 0 else -1 53 | 54 | def getRear(self) -> int: 55 | return self.tail.prev.val if self.size > 0 else -1 56 | 57 | def isEmpty(self) -> bool: 58 | return self.size == 0 59 | 60 | def isFull(self) -> bool: 61 | return self.size == self.capacity 62 | 63 | 64 | # Example usage: 65 | myCircularDeque = MyCircularDeque(3) 66 | print(myCircularDeque.insertLast(1)) # Output: True 67 | print(myCircularDeque.insertLast(2)) # Output: True 68 | print(myCircularDeque.insertFront(3)) # Output: True 69 | print(myCircularDeque.insertFront(4)) # Output: False 70 | print(myCircularDeque.getRear()) # Output: 2 71 | print(myCircularDeque.isFull()) # Output: True 72 | print(myCircularDeque.deleteLast()) # Output: True 73 | print(myCircularDeque.insertFront(4)) # Output: True 74 | print(myCircularDeque.getFront()) # Output: 4 75 | -------------------------------------------------------------------------------- /My_Learning/Day_6/Sets: -------------------------------------------------------------------------------- 1 | In Python, a set is a built-in data type that represents an unordered collection of unique elements. Sets are useful for tasks that involve membership testing and eliminating duplicate entries. Here's an overview of sets in Python: 2 | 3 | ### **Set Basics:** 4 | 5 | - **Definition:** An unordered collection of unique elements enclosed in curly braces **`{}`** or created using the **`set()`** constructor. 6 | 7 | ```python 8 | 9 | my_set = {1, 2, 3, 3, 4} 10 | 11 | ``` 12 | 13 | - **Example:** The duplicates are automatically removed, and the set contains only unique elements: **`{1, 2, 3, 4}`**. 14 | 15 | ### **Common Operations:** 16 | 17 | 1. **Adding Elements:** 18 | - Use the **`add()`** method to add a single element. 19 | 20 | ```python 21 | 22 | my_set.add(5) 23 | 24 | ``` 25 | 26 | - Use the **`update()`** method to add multiple elements. 27 | 28 | ```python 29 | 30 | my_set.update({6, 7}) 31 | 32 | ``` 33 | 34 | 2. **Removing Elements:** 35 | - Use the **`remove()`** or **`discard()`** method to remove an element. 36 | 37 | ```python 38 | 39 | my_set.remove(3) 40 | 41 | ``` 42 | 43 | - The difference between **`remove()`** and **`discard()`** is that **`remove()`** raises an error if the element is not present, while **`discard()`** does not. 44 | 3. **Set Operations:** 45 | - Sets support various operations like union, intersection, difference, and symmetric difference. 46 | 47 | ```python 48 | 49 | set1 = {1, 2, 3} 50 | set2 = {3, 4, 5} 51 | 52 | union_set = set1 | set2 # Union: {1, 2, 3, 4, 5} 53 | intersection_set = set1 & set2 # Intersection: {3} 54 | difference_set = set1 - set2 # Difference: {1, 2} 55 | symmetric_difference_set = set1 ^ set2 # Symmetric Difference: {1, 2, 4, 5} 56 | 57 | ``` 58 | 59 | 4. **Membership Testing:** 60 | - Check if an element is present in a set. 61 | 62 | ```python 63 | 64 | is_present = 3 in my_set 65 | 66 | ``` 67 | 68 | 5. **Length of a Set:** 69 | - Get the number of elements in a set. 70 | 71 | ```python 72 | 73 | length = len(my_set) 74 | 75 | ``` 76 | 77 | 6. **Clearing a Set:** 78 | - Remove all elements from a set. 79 | 80 | ```python 81 | 82 | my_set.clear() 83 | 84 | ``` 85 | 86 | 87 | Sets are useful when you need to handle collections of unique items and perform set operations like intersection, union, and difference. Keep in mind that sets do not support indexing, and the order of elements is not guaranteed. 88 | -------------------------------------------------------------------------------- /My_Learning/Day_71/ques: -------------------------------------------------------------------------------- 1 | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). 2 | 3 | The algorithm for myAtoi(string s) is as follows: 4 | 5 | Read in and ignore any leading whitespace. 6 | Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 7 | Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 8 | Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). 9 | If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. 10 | Return the integer as the final result. 11 | Note: 12 | 13 | Only the space character ' ' is considered a whitespace character. 14 | Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. 15 | 16 | 17 | Example 1: 18 | 19 | Input: s = "42" 20 | Output: 42 21 | Explanation: The underlined characters are what is read in, the caret is the current reader position. 22 | Step 1: "42" (no characters read because there is no leading whitespace) 23 | ^ 24 | Step 2: "42" (no characters read because there is neither a '-' nor '+') 25 | ^ 26 | Step 3: "42" ("42" is read in) 27 | ^ 28 | The parsed integer is 42. 29 | Since 42 is in the range [-231, 231 - 1], the final result is 42. 30 | Example 2: 31 | 32 | Input: s = " -42" 33 | Output: -42 34 | Explanation: 35 | Step 1: " -42" (leading whitespace is read and ignored) 36 | ^ 37 | Step 2: " -42" ('-' is read, so the result should be negative) 38 | ^ 39 | Step 3: " -42" ("42" is read in) 40 | ^ 41 | The parsed integer is -42. 42 | Since -42 is in the range [-231, 231 - 1], the final result is -42. 43 | Example 3: 44 | 45 | Input: s = "4193 with words" 46 | Output: 4193 47 | Explanation: 48 | Step 1: "4193 with words" (no characters read because there is no leading whitespace) 49 | ^ 50 | Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') 51 | ^ 52 | Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) 53 | ^ 54 | The parsed integer is 4193. 55 | Since 4193 is in the range [-231, 231 - 1], the final result is 4193. 56 | 57 | -------------------------------------------------------------------------------- /My_Learning/Day_8/Dictionary: -------------------------------------------------------------------------------- 1 | In Python, a tuple is a collection of ordered and immutable elements. Here are some key characteristics and operations related to tuples: 2 | 3 | 1. **Creation:** 4 | - Tuples are created by placing a sequence of values separated by commas inside parentheses **`()`**. 5 | 6 | ```python 7 | 8 | my_tuple = (1, 2, 3, 'hello') 9 | 10 | ``` 11 | 12 | 2. **Accessing Elements:** 13 | - Elements of a tuple are accessed using indexing, similar to lists. 14 | 15 | ```python 16 | 17 | print(my_tuple[0]) # Output: 1 18 | 19 | ``` 20 | 21 | 3. **Immutable:** 22 | - Tuples are immutable, meaning once they are created, their elements cannot be changed or modified. 23 | 24 | ```python 25 | 26 | # This will raise an error 27 | my_tuple[0] = 5 28 | 29 | ``` 30 | 31 | 4. **Length:** 32 | - You can find the length (number of elements) of a tuple using the **`len()`** function. 33 | 34 | ```python 35 | 36 | print(len(my_tuple)) 37 | 38 | ``` 39 | 40 | 5. **Slicing:** 41 | - You can use slicing to extract a portion of the tuple. 42 | 43 | ```python 44 | 45 | subset_tuple = my_tuple[1:3] 46 | 47 | ``` 48 | 49 | 6. **Concatenation:** 50 | - Tuples can be concatenated using the **`+`** operator. 51 | 52 | ```python 53 | 54 | new_tuple = my_tuple + (4, 5, 6) 55 | 56 | ``` 57 | 58 | 7. **Repetition:** 59 | - Tuples can be repeated using the **``** operator. 60 | 61 | ```python 62 | 63 | repeated_tuple = my_tuple * 2 64 | 65 | ``` 66 | 67 | 8. **Deleting:** 68 | - You cannot delete elements of a tuple, but you can delete the entire tuple. 69 | 70 | ```python 71 | 72 | del my_tuple 73 | 74 | ``` 75 | 76 | 9. **Nested Tuples:** 77 | - Tuples can contain other tuples, creating nested structures. 78 | 79 | ```python 80 | 81 | nested_tuple = (1, (2, 3), 'hello') 82 | 83 | ``` 84 | 85 | 86 | Tuples are often used when you want to create an immutable sequence of elements. They are commonly used in scenarios where the data should not be modified after creation. 87 | 88 | In Python, a tuple is a collection of ordered and immutable elements. Here are some key characteristics and operations related to tuples: 89 | 90 | 1. **Creation:** 91 | - Tuples are created by placing a sequence of values separated by commas inside parentheses **`()`**. 92 | 93 | ```python 94 | 95 | my_tuple = (1, 2, 3, 'hello') 96 | 97 | ``` 98 | 99 | 2. **Accessing Elements:** 100 | - Elements of a tuple are accessed using indexing, similar to lists. 101 | 102 | ```python 103 | 104 | print(my_tuple[0]) # Output: 1 105 | ``` 106 | 107 | 3. **Immutable:** 108 | - Tuples are immutable, meaning once they are created, their elements cannot be changed or modified. 109 | 110 | ```python 111 | pythonCopy code 112 | # This will raise an error 113 | my_tuple[0] = 5 114 | 115 | ``` 116 | 117 | 4. **Length:** 118 | - You can find the length (number of elements) of a tuple using the **`len()`** function. 119 | 120 | ```python 121 | 122 | print(len(my_tuple)) 123 | 124 | ``` 125 | 126 | 5. **Slicing:** 127 | - You can use slicing to extract a portion of the tuple. 128 | 129 | ```python 130 | 131 | subset_tuple = my_tuple[1:3] 132 | 133 | ``` 134 | 135 | 6. **Concatenation:** 136 | - Tuples can be concatenated using the **`+`** operator. 137 | 138 | ```python 139 | 140 | new_tuple = my_tuple + (4, 5, 6) 141 | 142 | ``` 143 | 144 | 7. **Repetition:** 145 | - Tuples can be repeated using the **``** operator. 146 | 147 | ```python 148 | 149 | repeated_tuple = my_tuple * 2 150 | 151 | ``` 152 | 153 | 8. **Deleting:** 154 | - You cannot delete elements of a tuple, but you can delete the entire tuple. 155 | 156 | ```python 157 | 158 | del my_tuple 159 | 160 | ``` 161 | 162 | 9. **Nested Tuples:** 163 | - Tuples can contain other tuples, creating nested structures. 164 | 165 | ```python 166 | 167 | nested_tuple = (1, (2, 3), 'hello') 168 | 169 | ``` 170 | 171 | 172 | Tuples are often used when you want to create an immutable sequence of elements. They are commonly used in scenarios where the data should not be modified after creation. 173 | 174 | In Python, a tuple is a collection of ordered and immutable elements. Here are some key characteristics and operations related to tuples: 175 | 176 | 1. **Creation:** 177 | - Tuples are created by placing a sequence of values separated by commas inside parentheses **`()`**. 178 | 179 | ```python 180 | 181 | my_tuple = (1, 2, 3, 'hello') 182 | 183 | ``` 184 | 185 | 2. **Accessing Elements:** 186 | - Elements of a tuple are accessed using indexing, similar to lists. 187 | 188 | ```python 189 | 190 | print(my_tuple[0]) # Output: 1 191 | 192 | ``` 193 | 194 | 3. **Immutable:** 195 | - Tuples are immutable, meaning once they are created, their elements cannot be changed or modified. 196 | 197 | ```python 198 | 199 | # This will raise an error 200 | my_tuple[0] = 5 201 | 202 | ``` 203 | 204 | 4. **Length:** 205 | - You can find the length (number of elements) of a tuple using the **`len()`** function. 206 | 207 | ```python 208 | 209 | print(len(my_tuple)) 210 | 211 | ``` 212 | 213 | 5. **Slicing:** 214 | - You can use slicing to extract a portion of the tuple. 215 | 216 | ```python 217 | 218 | subset_tuple = my_tuple[1:3] 219 | 220 | ``` 221 | 222 | 6. **Concatenation:** 223 | - Tuples can be concatenated using the **`+`** operator. 224 | 225 | ```python 226 | new_tuple = my_tuple + (4, 5, 6) 227 | 228 | ``` 229 | 230 | 7. **Repetition:** 231 | - Tuples can be repeated using the **``** operator. 232 | 233 | ```python 234 | 235 | repeated_tuple = my_tuple * 2 236 | 237 | ``` 238 | 239 | 8. **Deleting:** 240 | - You cannot delete elements of a tuple, but you can delete the entire tuple. 241 | 242 | ```python 243 | 244 | del my_tuple 245 | 246 | ``` 247 | 248 | 9. **Nested Tuples:** 249 | - Tuples can contain other tuples, creating nested structures. 250 | 251 | ```python 252 | 253 | nested_tuple = (1, (2, 3), 'hello') 254 | 255 | ``` 256 | 257 | 258 | Tuples are often used when you want to create an immutable sequence of elements. They are commonly used in scenarios where the data should not be modified after creation. 259 | --------------------------------------------------------------------------------