├── 01_Intro_to_Dsa ├── Basic_C++ │ ├── 05_arrays_and_strings.md │ ├── 08_function.md │ └── 06_for_loop.md ├── STL_C++ │ ├── STL.C++ │ ├── 01_Intro _stl.md │ ├── 04_set.md │ └── 02_unordered_set.md ├── Patterns │ ├── 02_right_angled_triangle.md │ ├── 03_right_angled_number.md │ ├── 01_rectangular_star.md │ ├── 05_inverted_right_pyramid.md │ ├── 06_inverted_numbered_right_pyramid.md │ ├── 10_half_diamond_star.md │ ├── 04_right_angled_triangle_prymaid.md │ ├── 11_binary_number_triangle.md │ ├── 08_ inverted_star_pyramid.md │ ├── 07_star_pyramid.md │ ├── 12_number_crown.md │ └── 22_number_pattern.md ├── Basic_Math │ ├── 04_gcd_of_two_numbers.md │ └── 06_print_all_divisors.md └── Recursion │ ├── Extra_Problems │ ├── 04_sum_of_n_numbers.md │ ├── 03_power_using_recursion.md │ └── 01_factorial_using_recursion.md │ └── 01_introduction_to_recursion.md ├── Dsa_leetcode_problems ├── 1086-divisor-game │ ├── 1086-divisor-game.cpp │ └── README.md ├── 2575-minimum-cuts-to-divide-a-circle │ ├── 2575-minimum-cuts-to-divide-a-circle.cpp │ └── README.md ├── 0231-power-of-two │ ├── 0231-power-of-two.cpp │ └── README.md ├── 0342-power-of-four │ ├── 0342-power-of-four.cpp │ └── README.md ├── 0326-power-of-three │ ├── 0326-power-of-three.cpp │ └── README.md ├── 0242-valid-anagram │ ├── 0242-valid-anagram.cpp │ └── README.md ├── 1013-fibonacci-number │ ├── 1013-fibonacci-number.cpp │ └── README.md ├── 0172-factorial-trailing-zeroes │ ├── 0172-factorial-trailing-zeroes.cpp │ └── README.md ├── 0171-excel-sheet-column-number │ ├── 0171-excel-sheet-column-number.cpp │ └── README.md ├── 1448-maximum-69-number │ ├── 1448-maximum-69-number.cpp │ └── README.md ├── 0189-rotate-array │ ├── 0189-rotate-array.cpp │ └── README.md ├── 0441-arranging-coins │ ├── 0441-arranging-coins.cpp │ └── README.md ├── 3371-harshad-number │ ├── 3371-harshad-number.cpp │ └── README.md ├── 0507-perfect-number │ ├── 0507-perfect-number.cpp │ └── README.md ├── 0268-missing-number │ ├── 0268-missing-number.cpp │ └── README.md ├── 1950-sign-of-the-product-of-an-array │ ├── 1950-sign-of-the-product-of-an-array.cpp │ └── README.md ├── 0026-remove-duplicates-from-sorted-array │ ├── 0026-remove-duplicates-from-sorted-array.cpp │ └── README.md ├── 0168-excel-sheet-column-title │ ├── 0168-excel-sheet-column-title.cpp │ └── README.md ├── 0136-single-number │ ├── 0136-single-number.cpp │ └── README.md ├── 0900-reordered-power-of-2 │ ├── 0900-reordered-power-of-2.cpp │ └── README.md ├── 0485-max-consecutive-ones │ ├── 0485-max-consecutive-ones.cpp │ └── README.md ├── 0007-reverse-integer │ ├── 0007-reverse-integer.cpp │ └── README.md ├── 0009-palindrome-number │ ├── 0009-palindrome-number.cpp │ └── README.md ├── 0792-binary-search │ ├── 0792-binary-search.cpp │ └── README.md ├── 0121-best-time-to-buy-and-sell-stock │ ├── 0121-best-time-to-buy-and-sell-stock.cpp │ └── README.md ├── 4008-restore-finishing-order │ ├── 4008-restore-finishing-order.cpp │ └── README.md ├── 2432-number-of-zero-filled-subarrays │ ├── 2432-number-of-zero-filled-subarrays.cpp │ └── README.md ├── 0001-two-sum │ ├── 0001-two-sum.cpp │ └── README.md ├── 0053-maximum-subarray │ ├── 0053-maximum-subarray.cpp │ └── README.md ├── 0118-pascals-triangle │ ├── 0118-pascals-triangle.cpp │ └── README.md ├── 2346-largest-3-same-digit-number-in-string │ ├── 2346-largest-3-same-digit-number-in-string.cpp │ └── README.md ├── 2271-rearrange-array-elements-by-sign │ ├── 2271-rearrange-array-elements-by-sign.cpp │ └── README.md ├── 0075-sort-colors │ ├── 0075-sort-colors.cpp │ └── README.md ├── 1878-check-if-array-is-sorted-and-rotated │ ├── 1878-check-if-array-is-sorted-and-rotated.cpp │ └── README.md ├── 0169-majority-element │ ├── 0169-majority-element.cpp │ └── README.md ├── 0031-next-permutation │ └── 0031-next-permutation.cpp ├── 2882-ways-to-express-an-integer-as-sum-of-powers │ ├── 2882-ways-to-express-an-integer-as-sum-of-powers.cpp │ └── README.md ├── 2529-range-product-queries-of-powers │ ├── 2529-range-product-queries-of-powers.cpp │ └── README.md └── 0679-24-game │ ├── 0679-24-game.cpp │ └── README.md ├── .vscode ├── c_cpp_properties.json ├── launch.json ├── tasks.json └── settings.json ├── 1646-kth-missing-positive-number ├── 1646-kth-missing-positive-number.cpp └── README.md ├── 0035-search-insert-position ├── 0035-search-insert-position.cpp └── README.md ├── 0034-find-first-and-last-position-of-element-in-sorted-array ├── 0034-find-first-and-last-position-of-element-in-sorted-array.cpp └── README.md ├── 0141-linked-list-cycle ├── 0141-linked-list-cycle.cpp └── README.md ├── 0162-find-peak-element ├── 0162-find-peak-element.cpp └── README.md ├── 0908-middle-of-the-linked-list ├── 0908-middle-of-the-linked-list.java ├── 0908-middle-of-the-linked-list.cpp └── README.md ├── 0153-find-minimum-in-rotated-sorted-array ├── 0153-find-minimum-in-rotated-sorted-array.cpp └── README.md ├── 1408-find-the-smallest-divisor-given-a-threshold ├── 1408-find-the-smallest-divisor-given-a-threshold.cpp └── README.md ├── 0206-reverse-linked-list ├── 0206-reverse-linked-list.cpp └── README.md ├── 0033-search-in-rotated-sorted-array ├── 0033-search-in-rotated-sorted-array.cpp └── README.md ├── 0081-search-in-rotated-sorted-array-ii ├── 0081-search-in-rotated-sorted-array-ii.cpp └── README.md ├── 0410-split-array-largest-sum ├── 0410-split-array-largest-sum.cpp └── README.md ├── 0907-koko-eating-bananas ├── 0907-koko-eating-bananas.cpp └── README.md ├── 1056-capacity-to-ship-packages-within-d-days ├── 1056-capacity-to-ship-packages-within-d-days.cpp └── README.md ├── 0540-single-element-in-a-sorted-array ├── README.md └── 0540-single-element-in-a-sorted-array.cpp ├── 1605-minimum-number-of-days-to-make-m-bouquets ├── 1605-minimum-number-of-days-to-make-m-bouquets.cpp └── README.md ├── 0004-median-of-two-sorted-arrays ├── 0004-median-of-two-sorted-arrays.cpp └── README.md ├── 02_Sorting └── sorting.cpp └── 03_Arrays └── 01_Easy_problems ├── 08_linear_search.md ├── 11_max_consecutive_ones.md └── 07_move_zeros_to_end.md /01_Intro_to_Dsa/Basic_C++/05_arrays_and_strings.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1086-divisor-game/1086-divisor-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool divisorGame(int n) { 4 | return n%2==0; 5 | } 6 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2575-minimum-cuts-to-divide-a-circle/2575-minimum-cuts-to-divide-a-circle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfCuts(int n) { 4 | if(n==1) return 0; 5 | return(n%2==0?n/2:n); 6 | } 7 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0231-power-of-two/0231-power-of-two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if (n <= 0) return false; 5 | while (n % 2 == 0) n /= 2; 6 | return n == 1; 7 | } 8 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0342-power-of-four/0342-power-of-four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | if(n<=0) return false; 5 | while(n%4==0){ 6 | n/=4; 7 | } 8 | return n==1; 9 | } 10 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0326-power-of-three/0326-power-of-three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if(n<=0) return false; 5 | while(n%3==0){ 6 | n/=3; 7 | } 8 | return n==1; 9 | } 10 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0242-valid-anagram/0242-valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if(s.length()!=t.length()) return false; 5 | sort(s.begin(),s.end()); 6 | sort(t.begin(),t.end()); 7 | return s==t; 8 | } 9 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1013-fibonacci-number/1013-fibonacci-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int n) { 4 | if(n<=1){ 5 | return n; 6 | } 7 | int last=fib(n-1); 8 | int slast=fib(n-2); 9 | return last+slast; 10 | } 11 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0172-factorial-trailing-zeroes/0172-factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int count=0; 5 | while(n>=5){ 6 | count+=n/5; 7 | n/=5; 8 | } 9 | return count; 10 | } 11 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0171-excel-sheet-column-number/0171-excel-sheet-column-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string columnTitle) { 4 | int result=0; 5 | for(char c:columnTitle){ 6 | result=result * 26+(c-'A'+1); 7 | } 8 | return result; 9 | } 10 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1448-maximum-69-number/1448-maximum-69-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximum69Number (int num) { 4 | string s = to_string(num); 5 | for(char &c:s){ 6 | if(c=='6'){ 7 | c='9'; 8 | break; 9 | } 10 | } 11 | return stoi(s); 12 | } 13 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0189-rotate-array/0189-rotate-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n=nums.size(); 5 | k=k%n; 6 | reverse(nums.begin(),nums.end()); 7 | reverse(nums.begin(),nums.begin()+k); 8 | reverse(nums.begin()+k,nums.end()); 9 | } 10 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0441-arranging-coins/0441-arranging-coins.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrangeCoins(int n) { 4 | int row=0; 5 | int CoinStart=1; 6 | while(CoinStart<=n){ 7 | n-=CoinStart; 8 | row++; 9 | CoinStart++; 10 | } 11 | return row; 12 | } 13 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/3371-harshad-number/3371-harshad-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sumOfTheDigitsOfHarshadNumber(int x) { 4 | int sum=0; 5 | int temp=x; 6 | while(x>0){ 7 | int ldigit=x%10; 8 | sum+=ldigit; 9 | x/=10; 10 | } 11 | return (temp % sum == 0) ? sum : -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0507-perfect-number/0507-perfect-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPerfectNumber(int num) { 4 | 5 | int sum=0; 6 | for(int i=1;i<=num/2;i++){ 7 | if(num%i==0) 8 | sum+=i; 9 | } 10 | if(sum==num) return true; 11 | else return false; 12 | 13 | 14 | } 15 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0268-missing-number/0268-missing-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int n=nums.size(); 5 | int xor1=0; 6 | int xor2=0; 7 | for(int i=0;i& nums) { 4 | int sign=1; 5 | for(int i=0;i& nums) { 4 | int i=0; 5 | for(int j=1;j0){ 6 | columnNumber--; 7 | char c='A'+(columnNumber % 26); 8 | result=c+result; 9 | columnNumber/=26; 10 | } 11 | return result; 12 | } 13 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0136-single-number/0136-single-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int n=nums.size(); 5 | map mpp; 6 | for(int i=0;i& nums) { 4 | int maxi=0; 5 | int cnt=0; 6 | for(int i=0;i& arr, int k) { 4 | int n=arr.size(); 5 | int low=0,high=n-1; 6 | while(low<=high){ 7 | int mid=(low+high)/2; 8 | int missing=arr[mid]-(mid+1); 9 | if(missingINT_MAX/10 || reverse 0) { 10 | int lastdigit = x % 10; 11 | reverse = reverse * 10 + lastdigit; 12 | x = x / 10; 13 | } 14 | 15 | return reverse == dum; 16 | } 17 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0792-binary-search/0792-binary-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int low=0; 5 | int high =nums.size()-1; 6 | while(low<=high){ 7 | int mid=low+(high-low)/2; 8 | if(nums[mid]==target) return mid; 9 | else if( target> nums[mid]) low=mid+1; 10 | else high=mid-1; 11 | } 12 | return -1; 13 | } 14 | }; -------------------------------------------------------------------------------- /0035-search-insert-position/0035-search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int low=0,high=nums.size()-1; 5 | int ans=nums.size(); 6 | while(low<=high){ 7 | int mid=(low+high)/2; 8 | if(nums[mid]>=target){ 9 | ans=mid; 10 | high=mid-1; 11 | }else low=mid+1; 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int n=prices.size(); 5 | int mini=prices[0]; 6 | int profit=0; 7 | for(int i=1;i recoverOrder(vector& order, vector& friends) { 4 | int n=order.size(); 5 | vector isFriend(n+1,0); 6 | for(int x:friends)isFriend[x]=1; 7 | vectorans; 8 | ans.reserve(friends.size()); 9 | for(int x:order) 10 | if(isFriend[x]) ans.push_back(x); 11 | return ans; 12 | } 13 | }; -------------------------------------------------------------------------------- /0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int first=-1,last=-1; 5 | for(int i=0;i& nums) { 4 | long long cnt = 0, streak = 0; 5 | for (int num : nums) { 6 | if (num == 0) { 7 | streak++; 8 | cnt += streak; 9 | } else { 10 | streak = 0; 11 | } 12 | } 13 | return cnt; 14 | } 15 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0001-two-sum/0001-two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int n=nums.size(); 5 | mapmpp; 6 | for(int i=0;i& nums) { 4 | int n=nums.size(); 5 | int maxi=INT_MIN; 6 | int sum=0; 7 | for(int i=0;imaxi){ 10 | maxi=sum; 11 | } 12 | if(sum<0){ 13 | sum=0; 14 | } 15 | } 16 | return maxi; 17 | } 18 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0118-pascals-triangle/0118-pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> triangle; 5 | for(int i = 0; i < numRows; ++i) { 6 | vector row(i+1, 1); 7 | for(int j = 1; j < i; ++j) { 8 | row[j] = triangle[i-1][j-1] + triangle[i-1][j]; 9 | } 10 | triangle.push_back(row); 11 | } 12 | return triangle; 13 | } 14 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2346-largest-3-same-digit-number-in-string/2346-largest-3-same-digit-number-in-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestGoodInteger(string num) { 4 | string ans = ""; 5 | for (int i = 0; i <= num.size() - 3; ++i) { 6 | if (num[i] == num[i+1] && num[i+1] == num[i+2]) { 7 | string curr = num.substr(i, 3); 8 | if (curr > ans) ans = curr; 9 | } 10 | } 11 | return ans; 12 | } 13 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2271-rearrange-array-elements-by-sign/2271-rearrange-array-elements-by-sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int n=nums.size(); 5 | vector ans(n,0); 6 | int posIndex=0,negIndex=1; 7 | for(int i=0;impp; 13 | ListNode* temp=head; 14 | while(temp!=NULL){ 15 | if(mpp.find(temp)!=mpp.end()) return true; 16 | 17 | mpp[temp]=1; 18 | temp=temp->next; 19 | } 20 | return false; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /0162-find-peak-element/0162-find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | int n=nums.size(); 5 | int low=1,high=n-2; 6 | if(n==1) return 0; 7 | if(nums[0]>nums[1]) return 0; 8 | if(nums[n-1]>nums[n-2]) return n-1; 9 | while(low<=high){ 10 | int mid=(low+high)/2; 11 | if(nums[mid]>nums[mid-1]&&nums[mid]>nums[mid+1]) return mid; 12 | else if(nums[mid]>nums[mid-1]) 13 | low=mid+1; 14 | else 15 | high=mid-1; 16 | } 17 | return -1; 18 | } 19 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0075-sort-colors/0075-sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int n=nums.size(); 5 | int cnt0=0,cnt1=0,cnt2=0; 6 | for(int i=0;i& nums) { 4 | int n = nums.size(); 5 | int count = 0; 6 | 7 | for (int i = 0; i < n; i++) { 8 | // Compare current and next (with wraparound using %) 9 | if (nums[i] > nums[(i + 1) % n]) { 10 | count++; 11 | } 12 | // More than one drop means it's not a rotated sorted array 13 | if (count > 1) return false; 14 | } 15 | return true; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0169-majority-element/0169-majority-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int n=nums.size(); 5 | int cnt=0,ele; 6 | for(int i=0;in/2) 19 | return ele; 20 | return -1; 21 | } 22 | }; -------------------------------------------------------------------------------- /0908-middle-of-the-linked-list/0908-middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode middleNode(ListNode head) { 13 | ListNode slow=head; 14 | ListNode fast=head; 15 | while(fast!=null&&fast.next!=null){ 16 | slow=slow.next; 17 | fast=fast.next.next; 18 | } 19 | return slow; 20 | } 21 | } -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0031-next-permutation/0031-next-permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | int n=nums.size(); 5 | int idx=-1; 6 | for(int i=n-2;i>=0;i--){ 7 | if(nums[i]=0;i--){ 17 | if(nums[i]>nums[idx]){ 18 | swap(nums[i],nums[idx]); 19 | break; 20 | } 21 | } 22 | reverse(nums.begin()+idx+1,nums.end()); 23 | } 24 | }; -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n=nums.size(); 5 | int low=0,high=n-1; 6 | int ans=INT_MAX; 7 | while(low<=high){ 8 | int mid=(low+high)/2; 9 | if(nums[low]<=nums[high]){ 10 | ans=min(ans,nums[low]); 11 | break; 12 | } 13 | if(nums[low]<=nums[mid]){ 14 | ans=min(ans,nums[low]); 15 | low=mid+1; 16 | } 17 | else{ 18 | ans=min(ans,nums[mid]); 19 | high=mid-1; 20 | } 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2882-ways-to-express-an-integer-as-sum-of-powers/2882-ways-to-express-an-integer-as-sum-of-powers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static constexpr int MOD = 1e9 + 7; 3 | unordered_map dp; 4 | int helper(int n, int x, int curr) { 5 | long long key = (long long)n * 1000 + curr; // unique key for (n, curr) 6 | if (dp.count(key)) return dp[key]; 7 | int val = pow(curr, x); 8 | if (val > n) return 0; 9 | if (val == n) return 1; 10 | int res = (helper(n - val, x, curr + 1) + helper(n, x, curr + 1)) % MOD; 11 | return dp[key] = res; 12 | } 13 | public: 14 | int numberOfWays(int n, int x) { 15 | dp.clear(); 16 | return helper(n, x, 1); 17 | } 18 | }; -------------------------------------------------------------------------------- /1408-find-the-smallest-divisor-given-a-threshold/1408-find-the-smallest-divisor-given-a-threshold.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sumofD(vector& nums,int div){ 4 | int n=nums.size(); 5 | double sum=0; 6 | for(int i=0;i& nums, int threshold) { 12 | int maxi=*max_element(nums.begin(),nums.end()); 13 | int low=1,high=maxi; 14 | while(low<=high){ 15 | int mid=(low+high)/2; 16 | if(sumofD(nums,mid)<=threshold){ 17 | high=mid-1; 18 | } else{ 19 | low=mid+1; 20 | } 21 | } 22 | return low; 23 | } 24 | }; -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "externalConsole": true, 11 | "cwd": "c:/Users/Admin/Downloads/DSA-leetcode/Dsa_leetcode_problems/0031-next-permutation", 12 | "program": "c:/Users/Admin/Downloads/DSA-leetcode/Dsa_leetcode_problems/0031-next-permutation/build/Debug/outDebug", 13 | "MIMode": "gdb", 14 | "miDebuggerPath": "gdb", 15 | "setupCommands": [ 16 | { 17 | "description": "Enable pretty-printing for gdb", 18 | "text": "-enable-pretty-printing", 19 | "ignoreFailures": true 20 | } 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /0206-reverse-linked-list/0206-reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | stack st; 15 | ListNode* temp=head; 16 | while(temp!=NULL){ 17 | st.push(temp->val); 18 | temp=temp->next; 19 | } 20 | temp=head; 21 | while(temp!=NULL){ 22 | temp->val=st.top(); 23 | st.pop(); 24 | temp=temp->next; 25 | } 26 | return head; 27 | } 28 | }; -------------------------------------------------------------------------------- /0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int n=nums.size(); 5 | int low=0,high=n-1; 6 | while(low<=high){ 7 | int mid =(low+high)/2; 8 | if(nums[mid]==target) return mid; 9 | if(nums[low]<=nums[mid]){ 10 | if(nums[low]<=target&&target<=nums[mid]){ 11 | high=mid-1; 12 | }else { 13 | low=mid+1; 14 | } 15 | }else{ 16 | if(nums[mid]<=target&&target<=nums[high]) { 17 | low=mid+1; 18 | }else{ 19 | high=mid-1; 20 | } 21 | } 22 | } 23 | return -1; 24 | } 25 | }; -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: g++.exe build active file", 6 | "command": "C:\\MinGW\\bin\\g++.exe", 7 | "args": [ 8 | "-fdiagnostics-color=always", 9 | "-g", 10 | "${file}", 11 | "-o", 12 | "${fileDirname}\\${fileBasenameNoExtension}.exe" 13 | ], 14 | "options": { 15 | "cwd": "${fileDirname}" 16 | }, 17 | "problemMatcher": [ 18 | "$gcc" 19 | ], 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "detail": "Task generated by Debugger." 25 | } 26 | ], 27 | "version": "2.0.0" 28 | } -------------------------------------------------------------------------------- /0081-search-in-rotated-sorted-array-ii/0081-search-in-rotated-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& nums, int target) { 4 | int n=nums.size(); 5 | int low=0,high=n-1; 6 | while(low<=high){ 7 | int mid=(low+high)/2; 8 | if(nums[mid]==target) return true; 9 | if(nums[low]==nums[mid]&& nums[mid]==nums[high]){ 10 | low=low+1; 11 | high=high-1; 12 | continue; 13 | } 14 | if(nums[low]<=nums[mid]){ 15 | if(nums[low]<=target&& target<=nums[mid]) 16 | high=mid-1; 17 | else low=mid+1; 18 | } else { 19 | if(nums[mid]<=target&& target<=nums[high]) 20 | low=mid+1; 21 | else high=mid-1; 22 | } 23 | } 24 | return false; 25 | } 26 | }; -------------------------------------------------------------------------------- /0410-split-array-largest-sum/0410-split-array-largest-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int StudentCount(vector nums,int page){ 4 | int student=1; 5 | int Maxpage=0; 6 | int n=nums.size(); 7 | for(int i=0;i& nums, int k) { 18 | int low=*max_element(nums.begin(),nums.end()); 19 | int high=accumulate(nums.begin(),nums.end(),0); 20 | while(low<=high){ 21 | int mid=(low+high)/2; 22 | int student=StudentCount(nums,mid); 23 | if(student>k){ 24 | low=mid+1; 25 | } else{ 26 | high=mid-1; 27 | } 28 | } 29 | return low; 30 | } 31 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0900-reordered-power-of-2/README.md: -------------------------------------------------------------------------------- 1 |

900. Reordered Power of 2

Medium


You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.

2 | 3 |

Return true if and only if we can do this so that the resulting number is a power of two.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 1
10 | Output: true
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: n = 10
17 | Output: false
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= n <= 109
  • 25 |
26 | -------------------------------------------------------------------------------- /0908-middle-of-the-linked-list/0908-middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* temp=head; 15 | int cnt=0; 16 | if(head==NULL){ 17 | return head; 18 | } 19 | while(temp!=NULL){ 20 | cnt++; 21 | temp=temp->next; 22 | } 23 | int mid=(cnt/2)+1; 24 | temp=head; 25 | while(temp!=NULL){ 26 | mid=mid-1; 27 | if(mid==0){ 28 | break; 29 | } 30 | temp=temp->next; 31 | } 32 | return temp; 33 | } 34 | }; -------------------------------------------------------------------------------- /0907-koko-eating-bananas/0907-koko-eating-bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int findMax(vector&piles){ 5 | int n=piles.size(); 6 | int maxi=INT_MIN; 7 | for(int i=0;i&piles,int h){ 13 | long long totalH=0; 14 | int n=piles.size(); 15 | for(int i=0;i& piles, int h) { 21 | int low=1,high=findMax(piles); 22 | while(low<=high){ 23 | int mid=(low+high)/2; 24 | long long totalHour=findTotalHour(piles,mid); 25 | if(totalHour<=h){ 26 | high=mid-1; 27 | } else{ 28 | low=mid+1; 29 | } 30 | } 31 | return low; 32 | } 33 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0118-pascals-triangle/README.md: -------------------------------------------------------------------------------- 1 |

118. Pascal's Triangle

Easy


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 |

Example 1:

7 |
Input: numRows = 5
 8 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
 9 | 

Example 2:

10 |
Input: numRows = 1
11 | Output: [[1]]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= numRows <= 30
  • 18 |
19 | -------------------------------------------------------------------------------- /1056-capacity-to-ship-packages-within-d-days/1056-capacity-to-ship-packages-within-d-days.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDays(vector& weights, int cap){ 4 | int load=0,days=1; 5 | int n=weights.size(); 6 | for(int i=0;icap){ 8 | days+=1; 9 | load=weights[i]; 10 | } 11 | else{ 12 | load+=weights[i]; 13 | } 14 | } 15 | return days; 16 | } 17 | int shipWithinDays(vector& weights, int days) { 18 | int low=*max_element(weights.begin(),weights.end()); 19 | int high=accumulate(weights.begin(),weights.end(),0); 20 | while(low<=high){ 21 | int mid=(low+high)/2; 22 | int noOfDays=findDays(weights,mid); 23 | if(noOfDays<=days){ 24 | high=mid-1; 25 | } else{ 26 | low=mid+1; 27 | } 28 | } 29 | return low; 30 | } 31 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0485-max-consecutive-ones/README.md: -------------------------------------------------------------------------------- 1 |

485. Max Consecutive Ones

Easy


Given a binary array nums, return the maximum number of consecutive 1's in the array.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,1,0,1,1,1]
 8 | Output: 3
 9 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: nums = [1,0,1,1,0,1]
16 | Output: 2
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • 1 <= nums.length <= 105
  • 24 |
  • nums[i] is either 0 or 1.
  • 25 |
26 | -------------------------------------------------------------------------------- /0540-single-element-in-a-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

540. Single Element in a Sorted Array

Medium


You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

2 | 3 |

Return the single element that appears only once.

4 | 5 |

Your solution must run in O(log n) time and O(1) space.

6 | 7 |

 

8 |

Example 1:

9 |
Input: nums = [1,1,2,3,3,4,4,8,8]
10 | Output: 2
11 | 

Example 2:

12 |
Input: nums = [3,3,7,7,10,11,11]
13 | Output: 10
14 | 
15 |

 

16 |

Constraints:

17 | 18 |
    19 |
  • 1 <= nums.length <= 105
  • 20 |
  • 0 <= nums[i] <= 105
  • 21 |
22 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2529-range-product-queries-of-powers/2529-range-product-queries-of-powers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int mod = 1e9+7; 4 | 5 | vector productQueries(int n, vector>& queries) { 6 | vector p2, res; 7 | int i = 0, k = 0; 8 | while (n) { 9 | if (n & 1) { 10 | p2.push_back(i); 11 | if (k) p2[k] += p2[k - 1]; // prefix sum of exponents 12 | k++; 13 | } 14 | n >>= 1; 15 | i++; 16 | } 17 | 18 | for (auto &q : queries) { 19 | int p = p2[q[1]] - (q[0] ? p2[q[0] - 1] : 0); 20 | res.push_back(fastPow(2, p)); 21 | } 22 | return res; 23 | } 24 | 25 | private: 26 | int fastPow(int base, int exp) { 27 | int res = 1; 28 | while (exp) { 29 | if (exp & 1) res = (1LL * res * base) % mod; 30 | base = (1LL * base * base) % mod; 31 | exp >>= 1; 32 | } 33 | return res; 34 | } 35 | }; -------------------------------------------------------------------------------- /1605-minimum-number-of-days-to-make-m-bouquets/1605-minimum-number-of-days-to-make-m-bouquets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(vector &arr, int day, int m, int k) { 4 | int n=arr.size(); 5 | int cnt=0,nofB=0; 6 | for(int i=0;i=m; 15 | } 16 | int minDays(vector& bloomDay, int m, int k) { 17 | int n=bloomDay.size(); 18 | if ((long long)m * k > n) return -1; 19 | int mini=*min_element(bloomDay.begin(),bloomDay.end()); 20 | int maxi=*max_element(bloomDay.begin(),bloomDay.end()); 21 | int low=mini,high=maxi; 22 | while(low<=high){ 23 | int mid=(low+high)/2; 24 | if(possible(bloomDay,mid,m,k)){ 25 | high=mid-1; 26 | } else { 27 | low=mid+1; 28 | } 29 | } 30 | return low; 31 | } 32 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0342-power-of-four/README.md: -------------------------------------------------------------------------------- 1 |

342. Power of Four

Easy


Given an integer n, return true if it is a power of four. Otherwise, return false.

2 | 3 |

An integer n is a power of four, if there exists an integer x such that n == 4x.

4 | 5 |

 

6 |

Example 1:

7 |
Input: n = 16
 8 | Output: true
 9 | 

Example 2:

10 |
Input: n = 5
11 | Output: false
12 | 

Example 3:

13 |
Input: n = 1
14 | Output: true
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • -231 <= n <= 231 - 1
  • 21 |
22 | 23 |

 

24 | Follow up: Could you solve it without loops/recursion? -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0169-majority-element/README.md: -------------------------------------------------------------------------------- 1 |

169. Majority Element

Easy


Given an array nums of size n, return the majority element.

2 | 3 |

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [3,2,3]
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: nums = [2,2,1,1,1,2,2]
11 | Output: 2
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • n == nums.length
  • 18 |
  • 1 <= n <= 5 * 104
  • 19 |
  • -109 <= nums[i] <= 109
  • 20 |
21 | 22 |

 

23 | Follow-up: Could you solve the problem in linear time and in O(1) space? -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0168-excel-sheet-column-title/README.md: -------------------------------------------------------------------------------- 1 |

168. Excel Sheet Column Title

Easy


Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

2 | 3 |

For example:

4 | 5 |
 6 | A -> 1
 7 | B -> 2
 8 | C -> 3
 9 | ...
10 | Z -> 26
11 | AA -> 27
12 | AB -> 28 
13 | ...
14 | 
15 | 16 |

 

17 |

Example 1:

18 | 19 |
20 | Input: columnNumber = 1
21 | Output: "A"
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: columnNumber = 28
28 | Output: "AB"
29 | 
30 | 31 |

Example 3:

32 | 33 |
34 | Input: columnNumber = 701
35 | Output: "ZY"
36 | 
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= columnNumber <= 231 - 1
  • 43 |
44 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0007-reverse-integer/README.md: -------------------------------------------------------------------------------- 1 |

7. Reverse Integer

Medium


Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

2 | 3 |

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: x = 123
10 | Output: 321
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: x = -123
17 | Output: -321
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: x = 120
24 | Output: 21
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • -231 <= x <= 231 - 1
  • 32 |
33 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0679-24-game/0679-24-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgePoint24(vector& cards) { 4 | vector nums(cards.begin(), cards.end()); 5 | return dfs(nums); 6 | } 7 | bool dfs(vector& nums) { 8 | if (nums.size() == 1) return abs(nums[0] - 24) < 1e-6; 9 | for (int i = 0; i < nums.size(); ++i) { 10 | for (int j = 0; j < nums.size(); ++j) { 11 | if (i == j) continue; 12 | vector next; 13 | for (int k = 0; k < nums.size(); ++k) 14 | if (k != i && k != j) next.push_back(nums[k]); 15 | for (auto val : compute(nums[i], nums[j])) { 16 | next.push_back(val); 17 | if (dfs(next)) return true; 18 | next.pop_back(); 19 | } 20 | } 21 | } 22 | return false; 23 | } 24 | vector compute(double a, double b) { 25 | vector res = {a + b, a - b, b - a, a * b}; 26 | if (fabs(b) > 1e-6) res.push_back(a / b); 27 | if (fabs(a) > 1e-6) res.push_back(b / a); 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0172-factorial-trailing-zeroes/README.md: -------------------------------------------------------------------------------- 1 |

172. Factorial Trailing Zeroes

Medium


Given an integer n, return the number of trailing zeroes in n!.

2 | 3 |

Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 3
10 | Output: 0
11 | Explanation: 3! = 6, no trailing zero.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 5
18 | Output: 1
19 | Explanation: 5! = 120, one trailing zero.
20 | 
21 | 22 |

Example 3:

23 | 24 |
25 | Input: n = 0
26 | Output: 0
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 0 <= n <= 104
  • 34 |
35 | 36 |

 

37 |

Follow up: Could you write a solution that works in logarithmic time complexity?

38 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0507-perfect-number/README.md: -------------------------------------------------------------------------------- 1 |

507. Perfect Number

Easy


A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

2 | 3 |

Given an integer n, return true if n is a perfect number, otherwise return false.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: num = 28
10 | Output: true
11 | Explanation: 28 = 1 + 2 + 4 + 7 + 14
12 | 1, 2, 4, 7, and 14 are all divisors of 28.
13 | 
14 | 15 |

Example 2:

16 | 17 |
18 | Input: num = 7
19 | Output: false
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= num <= 108
  • 27 |
28 | -------------------------------------------------------------------------------- /0540-single-element-in-a-sorted-array/0540-single-element-in-a-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& nums) { 4 | int n = nums.size(); // size of the array. 5 | 6 | // Edge cases: 7 | if (n == 1) return nums[0]; 8 | if (nums[0] != nums[1]) return nums[0]; 9 | if (nums[n - 1] != nums[n - 2]) return nums[n - 1]; 10 | 11 | int low = 1, high = n - 2; 12 | while (low <= high) { 13 | int mid = (low + high) / 2; 14 | 15 | // if nums[mid] is the single element: 16 | if (nums[mid] != nums[mid + 1] && nums[mid] != nums[mid - 1]) { 17 | return nums[mid]; 18 | } 19 | 20 | // we are in the left: 21 | if ((mid % 2 == 1 && nums[mid] == nums[mid - 1]) 22 | || (mid % 2 == 0 && nums[mid] == nums[mid + 1])) { 23 | // eliminate the left half: 24 | low = mid + 1; 25 | } 26 | // we are in the right: 27 | else { 28 | // eliminate the right half: 29 | high = mid - 1; 30 | } 31 | } 32 | 33 | // dummy return statement: 34 | return -1; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0231-power-of-two/README.md: -------------------------------------------------------------------------------- 1 |

231. Power of Two

Easy


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 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 1
10 | Output: true
11 | Explanation: 20 = 1
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 16
18 | Output: true
19 | Explanation: 24 = 16
20 | 
21 | 22 |

Example 3:

23 | 24 |
25 | Input: n = 3
26 | Output: false
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • -231 <= n <= 231 - 1
  • 34 |
35 | 36 |

 

37 | Follow up: Could you solve it without loops/recursion? -------------------------------------------------------------------------------- /01_Intro_to_Dsa/STL_C++/STL.C++: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | vector < int > v; 7 | 8 | for (int i = 0; i < 10; i++) { 9 | v.push_back(i); //inserting elements in the vector 10 | } 11 | 12 | cout << "the elements in the vector: "; 13 | for (auto it = v.begin(); it != v.end(); it++) 14 | cout << * it << " "; 15 | 16 | cout << "\nThe front element of the vector: " << v.front(); 17 | cout << "\nThe last element of the vector: " << v.back(); 18 | cout << "\nThe size of the vector: " << v.size(); 19 | cout << "\nDeleting element from the end: " << v[v.size() - 1]; 20 | v.pop_back(); 21 | 22 | cout << "\nPrinting the vector after removing the last element:" << endl; 23 | for (int i = 0; i < v.size(); i++) 24 | cout << v[i] << " "; 25 | 26 | cout << "\nInserting 5 at the beginning:" << endl; 27 | v.insert(v.begin(), 5); 28 | cout << "The first element is: " << v[0] << endl; 29 | cout << "Erasing the first element" << endl; 30 | v.erase(v.begin()); 31 | cout << "Now the first element is: " << v[0] << endl; 32 | 33 | if (v.empty()) 34 | cout << "\nvector is empty"; 35 | else 36 | cout << "\nvector is not empty" << endl; 37 | 38 | v.clear(); 39 | cout << "Size of the vector after clearing the vector: " << v.size(); 40 | 41 | } -------------------------------------------------------------------------------- /0004-median-of-two-sorted-arrays/0004-median-of-two-sorted-arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int n1 = nums1.size(), n2 = nums2.size(); 5 | int n=(n1+n2); 6 | int cnt=0,i=0,j=0; 7 | int idxlbl1=-1,idxlbl2=-1; 8 | int idx2=n/2,idx1=idx2-1; 9 | while(i 3 | using namespace std; 4 | void selection_sort(int arr[] ,int n){ 5 | for(int i=0;i<=n-2;i++){ 6 | int min=i; 7 | for(int j=i+1;j<=n-1;j++){ 8 | if(arr[j]=1;i--){ 19 | int swap=0; 20 | for(int j=0;j<=i-1;j++){ 21 | if(arr[j]>arr[j+1]){ 22 | int temp=arr[j+1]; 23 | arr[j+1]=arr[j]; 24 | arr[j]=temp; 25 | swap=1; 26 | } 27 | } 28 | if(swap==0){ 29 | break; 30 | } 31 | } 32 | cout<<"runs"<=0&&arr[j]>key){ 39 | arr[j+1]=arr[j]; 40 | j--; 41 | } 42 | arr[j+1]=key; 43 | } 44 | } 45 | int main() { 46 | int n; 47 | cin>>n; 48 | int arr[n]; 49 | for(int i=0;i>arr[i]; 51 | } 52 | insertion_sort(arr,n); 53 | for(int i=0;i1013. Fibonacci Number

Easy


The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

2 | 3 |
 4 | F(0) = 0, F(1) = 1
 5 | F(n) = F(n - 1) + F(n - 2), for n > 1.
 6 | 
7 | 8 |

Given n, calculate F(n).

9 | 10 |

 

11 |

Example 1:

12 | 13 |
14 | Input: n = 2
15 | Output: 1
16 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
17 | 
18 | 19 |

Example 2:

20 | 21 |
22 | Input: n = 3
23 | Output: 2
24 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
25 | 
26 | 27 |

Example 3:

28 | 29 |
30 | Input: n = 4
31 | Output: 3
32 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 0 <= n <= 30
  • 40 |
41 | -------------------------------------------------------------------------------- /0908-middle-of-the-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

908. Middle of the Linked List

Easy


Given the head of a singly linked list, return the middle node of the linked list.

2 | 3 |

If there are two middle nodes, return the second middle node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: head = [1,2,3,4,5]
10 | Output: [3,4,5]
11 | Explanation: The middle node of the list is node 3.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: head = [1,2,3,4,5,6]
18 | Output: [4,5,6]
19 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the list is in the range [1, 100].
  • 27 |
  • 1 <= Node.val <= 100
  • 28 |
29 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0242-valid-anagram/README.md: -------------------------------------------------------------------------------- 1 |

242. Valid Anagram

Easy


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
7 |

Input: s = "anagram", t = "nagaram"

8 | 9 |

Output: true

10 |
11 | 12 |

Example 2:

13 | 14 |
15 |

Input: s = "rat", t = "car"

16 | 17 |

Output: false

18 |
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= s.length, t.length <= 5 * 104
  • 25 |
  • s and t consist of lowercase English letters.
  • 26 |
27 | 28 |

 

29 |

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

30 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0326-power-of-three/README.md: -------------------------------------------------------------------------------- 1 |

326. Power of Three

Easy


Given an integer n, return true if it is a power of three. Otherwise, return false.

2 | 3 |

An integer n is a power of three, if there exists an integer x such that n == 3x.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 27
10 | Output: true
11 | Explanation: 27 = 33
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 0
18 | Output: false
19 | Explanation: There is no x where 3x = 0.
20 | 
21 | 22 |

Example 3:

23 | 24 |
25 | Input: n = -1
26 | Output: false
27 | Explanation: There is no x where 3x = (-1).
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • -231 <= n <= 231 - 1
  • 35 |
36 | 37 |

 

38 | Follow up: Could you solve it without loops/recursion? -------------------------------------------------------------------------------- /0206-reverse-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

206. Reverse Linked List

Easy


Given the head of a singly linked list, reverse the list, and return the reversed list.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: head = [1,2,3,4,5]
 8 | Output: [5,4,3,2,1]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: head = [1,2]
15 | Output: [2,1]
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: head = []
22 | Output: []
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the list is the range [0, 5000].
  • 30 |
  • -5000 <= Node.val <= 5000
  • 31 |
32 | 33 |

 

34 |

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

35 | -------------------------------------------------------------------------------- /0004-median-of-two-sorted-arrays/README.md: -------------------------------------------------------------------------------- 1 |

4. Median of Two Sorted Arrays

Hard


Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

2 | 3 |

The overall run time complexity should be O(log (m+n)).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums1 = [1,3], nums2 = [2]
10 | Output: 2.00000
11 | Explanation: merged array = [1,2,3] and median is 2.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums1 = [1,2], nums2 = [3,4]
18 | Output: 2.50000
19 | Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • nums1.length == m
  • 27 |
  • nums2.length == n
  • 28 |
  • 0 <= m <= 1000
  • 29 |
  • 0 <= n <= 1000
  • 30 |
  • 1 <= m + n <= 2000
  • 31 |
  • -106 <= nums1[i], nums2[i] <= 106
  • 32 |
33 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0171-excel-sheet-column-number/README.md: -------------------------------------------------------------------------------- 1 |

171. Excel Sheet Column Number

Easy


Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

2 | 3 |

For example:

4 | 5 |
 6 | A -> 1
 7 | B -> 2
 8 | C -> 3
 9 | ...
10 | Z -> 26
11 | AA -> 27
12 | AB -> 28 
13 | ...
14 | 
15 | 16 |

 

17 |

Example 1:

18 | 19 |
20 | Input: columnTitle = "A"
21 | Output: 1
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: columnTitle = "AB"
28 | Output: 28
29 | 
30 | 31 |

Example 3:

32 | 33 |
34 | Input: columnTitle = "ZY"
35 | Output: 701
36 | 
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= columnTitle.length <= 7
  • 43 |
  • columnTitle consists only of uppercase English letters.
  • 44 |
  • columnTitle is in the range ["A", "FXSHRXW"].
  • 45 |
46 | -------------------------------------------------------------------------------- /0035-search-insert-position/README.md: -------------------------------------------------------------------------------- 1 |

35. Search Insert Position

Easy


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 |

Example 1:

7 | 8 |
 9 | Input: nums = [1,3,5,6], target = 5
10 | Output: 2
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: nums = [1,3,5,6], target = 2
17 | Output: 1
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: nums = [1,3,5,6], target = 7
24 | Output: 4
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • 1 <= nums.length <= 104
  • 32 |
  • -104 <= nums[i] <= 104
  • 33 |
  • nums contains distinct values sorted in ascending order.
  • 34 |
  • -104 <= target <= 104
  • 35 |
36 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0792-binary-search/README.md: -------------------------------------------------------------------------------- 1 |

792. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

2 | 3 |

You must write an algorithm with O(log n) runtime complexity.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [-1,0,3,5,9,12], target = 9
10 | Output: 4
11 | Explanation: 9 exists in nums and its index is 4
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [-1,0,3,5,9,12], target = 2
18 | Output: -1
19 | Explanation: 2 does not exist in nums so return -1
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= nums.length <= 104
  • 27 |
  • -104 < nums[i], target < 104
  • 28 |
  • All the integers in nums are unique.
  • 29 |
  • nums is sorted in ascending order.
  • 30 |
31 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1086-divisor-game/README.md: -------------------------------------------------------------------------------- 1 |

1086. Divisor Game

Easy


Alice and Bob take turns playing a game, with Alice starting first.

2 | 3 |

Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:

4 | 5 |
    6 |
  • Choosing any x with 0 < x < n and n % x == 0.
  • 7 |
  • Replacing the number n on the chalkboard with n - x.
  • 8 |
9 | 10 |

Also, if a player cannot make a move, they lose the game.

11 | 12 |

Return true if and only if Alice wins the game, assuming both players play optimally.

13 | 14 |

 

15 |

Example 1:

16 | 17 |
18 | Input: n = 2
19 | Output: true
20 | Explanation: Alice chooses 1, and Bob has no more moves.
21 | 
22 | 23 |

Example 2:

24 | 25 |
26 | Input: n = 3
27 | Output: false
28 | Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= n <= 1000
  • 36 |
37 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0075-sort-colors/README.md: -------------------------------------------------------------------------------- 1 |

75. Sort Colors

Medium


Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

2 | 3 |

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

4 | 5 |

You must solve this problem without using the library's sort function.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [2,0,2,1,1,0]
12 | Output: [0,0,1,1,2,2]
13 | 
14 | 15 |

Example 2:

16 | 17 |
18 | Input: nums = [2,0,1]
19 | Output: [0,1,2]
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • n == nums.length
  • 27 |
  • 1 <= n <= 300
  • 28 |
  • nums[i] is either 0, 1, or 2.
  • 29 |
30 | 31 |

 

32 |

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

33 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0441-arranging-coins/README.md: -------------------------------------------------------------------------------- 1 |

441. Arranging Coins

Easy


You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

2 | 3 |

Given the integer n, return the number of complete rows of the staircase you will build.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 5
10 | Output: 2
11 | Explanation: Because the 3rd row is incomplete, we return 2.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 8
18 | Output: 3
19 | Explanation: Because the 4th row is incomplete, we return 3.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= n <= 231 - 1
  • 27 |
28 | -------------------------------------------------------------------------------- /0034-find-first-and-last-position-of-element-in-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

2 | 3 |

If target is not found in the array, return [-1, -1].

4 | 5 |

You must write an algorithm with O(log n) runtime complexity.

6 | 7 |

 

8 |

Example 1:

9 |
Input: nums = [5,7,7,8,8,10], target = 8
10 | Output: [3,4]
11 | 

Example 2:

12 |
Input: nums = [5,7,7,8,8,10], target = 6
13 | Output: [-1,-1]
14 | 

Example 3:

15 |
Input: nums = [], target = 0
16 | Output: [-1,-1]
17 | 
18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 0 <= nums.length <= 105
  • 23 |
  • -109 <= nums[i] <= 109
  • 24 |
  • nums is a non-decreasing array.
  • 25 |
  • -109 <= target <= 109
  • 26 |
27 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0009-palindrome-number/README.md: -------------------------------------------------------------------------------- 1 |

9. Palindrome Number

Easy


Given an integer x, return true if x is a palindrome, and false otherwise.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: x = 121
 8 | Output: true
 9 | Explanation: 121 reads as 121 from left to right and from right to left.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: x = -121
16 | Output: false
17 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: x = 10
24 | Output: false
25 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • -231 <= x <= 231 - 1
  • 33 |
34 | 35 |

 

36 | Follow up: Could you solve it without converting the integer to a string? -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0053-maximum-subarray/README.md: -------------------------------------------------------------------------------- 1 |

53. Maximum Subarray

Medium


Given an integer array nums, find the subarray with the largest sum, and return its sum.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
 8 | Output: 6
 9 | Explanation: The subarray [4,-1,2,1] has the largest sum 6.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: nums = [1]
16 | Output: 1
17 | Explanation: The subarray [1] has the largest sum 1.
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: nums = [5,4,-1,7,8]
24 | Output: 23
25 | Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 1 <= nums.length <= 105
  • 33 |
  • -104 <= nums[i] <= 104
  • 34 |
35 | 36 |

 

37 |

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

38 | -------------------------------------------------------------------------------- /0410-split-array-largest-sum/README.md: -------------------------------------------------------------------------------- 1 |

410. Split Array Largest Sum

Hard


Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.

2 | 3 |

Return the minimized largest sum of the split.

4 | 5 |

A subarray is a contiguous part of the array.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [7,2,5,10,8], k = 2
12 | Output: 18
13 | Explanation: There are four ways to split nums into two subarrays.
14 | The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: nums = [1,2,3,4,5], k = 2
21 | Output: 9
22 | Explanation: There are four ways to split nums into two subarrays.
23 | The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 1 <= nums.length <= 1000
  • 31 |
  • 0 <= nums[i] <= 106
  • 32 |
  • 1 <= k <= min(50, nums.length)
  • 33 |
34 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0121-best-time-to-buy-and-sell-stock/README.md: -------------------------------------------------------------------------------- 1 |

121. Best Time to Buy and Sell Stock

Easy


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 |

 

8 |

Example 1:

9 | 10 |
11 | Input: prices = [7,1,5,3,6,4]
12 | Output: 5
13 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
14 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: prices = [7,6,4,3,1]
21 | Output: 0
22 | Explanation: In this case, no transactions are done and the max profit = 0.
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= prices.length <= 105
  • 30 |
  • 0 <= prices[i] <= 104
  • 31 |
32 | -------------------------------------------------------------------------------- /1646-kth-missing-positive-number/README.md: -------------------------------------------------------------------------------- 1 |

1646. Kth Missing Positive Number

Easy


Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

2 | 3 |

Return the kth positive integer that is missing from this array.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: arr = [2,3,4,7,11], k = 5
10 | Output: 9
11 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: arr = [1,2,3,4], k = 2
18 | Output: 6
19 | Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= arr.length <= 1000
  • 27 |
  • 1 <= arr[i] <= 1000
  • 28 |
  • 1 <= k <= 1000
  • 29 |
  • arr[i] < arr[j] for 1 <= i < j <= arr.length
  • 30 |
31 | 32 |

 

33 |

Follow up:

34 | 35 |

Could you solve this problem in less than O(n) complexity?

36 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0136-single-number/README.md: -------------------------------------------------------------------------------- 1 |

136. Single Number

Easy


Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

2 | 3 |

You must implement a solution with a linear runtime complexity and use only constant extra space.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
9 |

Input: nums = [2,2,1]

10 | 11 |

Output: 1

12 |
13 | 14 |

Example 2:

15 | 16 |
17 |

Input: nums = [4,1,2,1,2]

18 | 19 |

Output: 4

20 |
21 | 22 |

Example 3:

23 | 24 |
25 |

Input: nums = [1]

26 | 27 |

Output: 1

28 |
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 1 <= nums.length <= 3 * 104
  • 35 |
  • -3 * 104 <= nums[i] <= 3 * 104
  • 36 |
  • Each element in the array appears twice except for one element which appears only once.
  • 37 |
38 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0189-rotate-array/README.md: -------------------------------------------------------------------------------- 1 |

189. Rotate Array

Medium


Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,2,3,4,5,6,7], k = 3
 8 | Output: [5,6,7,1,2,3,4]
 9 | Explanation:
10 | rotate 1 steps to the right: [7,1,2,3,4,5,6]
11 | rotate 2 steps to the right: [6,7,1,2,3,4,5]
12 | rotate 3 steps to the right: [5,6,7,1,2,3,4]
13 | 
14 | 15 |

Example 2:

16 | 17 |
18 | Input: nums = [-1,-100,3,99], k = 2
19 | Output: [3,99,-1,-100]
20 | Explanation: 
21 | rotate 1 steps to the right: [99,-1,-100,3]
22 | rotate 2 steps to the right: [3,99,-1,-100]
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= nums.length <= 105
  • 30 |
  • -231 <= nums[i] <= 231 - 1
  • 31 |
  • 0 <= k <= 105
  • 32 |
33 | 34 |

 

35 |

Follow up:

36 | 37 |
    38 |
  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • 39 |
  • Could you do it in-place with O(1) extra space?
  • 40 |
41 | -------------------------------------------------------------------------------- /0162-find-peak-element/README.md: -------------------------------------------------------------------------------- 1 |

162. Find Peak Element

Medium


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 |

 

10 |

Example 1:

11 | 12 |
13 | Input: nums = [1,2,3,1]
14 | Output: 2
15 | Explanation: 3 is a peak element and your function should return the index number 2.
16 | 17 |

Example 2:

18 | 19 |
20 | Input: nums = [1,2,1,3,5,6,4]
21 | Output: 5
22 | 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.
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • 1 <= nums.length <= 1000
  • 29 |
  • -231 <= nums[i] <= 231 - 1
  • 30 |
  • nums[i] != nums[i + 1] for all valid i.
  • 31 |
32 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/3371-harshad-number/README.md: -------------------------------------------------------------------------------- 1 |

3371. Harshad Number

Easy


An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
7 |

Input: x = 18

8 | 9 |

Output: 9

10 | 11 |

Explanation:

12 | 13 |

The sum of digits of x is 9. 18 is divisible by 9. So 18 is a Harshad number and the answer is 9.

14 |
15 | 16 |

Example 2:

17 | 18 |
19 |

Input: x = 23

20 | 21 |

Output: -1

22 | 23 |

Explanation:

24 | 25 |

The sum of digits of x is 5. 23 is not divisible by 5. So 23 is not a Harshad number and the answer is -1.

26 |
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 1 <= x <= 100
  • 33 |
34 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1448-maximum-69-number/README.md: -------------------------------------------------------------------------------- 1 |

1448. Maximum 69 Number

Easy


You are given a positive integer num consisting only of digits 6 and 9.

2 | 3 |

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: num = 9669
10 | Output: 9969
11 | Explanation: 
12 | Changing the first digit results in 6669.
13 | Changing the second digit results in 9969.
14 | Changing the third digit results in 9699.
15 | Changing the fourth digit results in 9666.
16 | The maximum number is 9969.
17 | 
18 | 19 |

Example 2:

20 | 21 |
22 | Input: num = 9996
23 | Output: 9999
24 | Explanation: Changing the last digit 6 to 9 results in the maximum number.
25 | 
26 | 27 |

Example 3:

28 | 29 |
30 | Input: num = 9999
31 | Output: 9999
32 | Explanation: It is better not to apply any change.
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 1 <= num <= 104
  • 40 |
  • num consists of only 6 and 9 digits.
  • 41 |
42 | -------------------------------------------------------------------------------- /1408-find-the-smallest-divisor-given-a-threshold/README.md: -------------------------------------------------------------------------------- 1 |

1408. Find the Smallest Divisor Given a Threshold

Medium


Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

2 | 3 |

Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

4 | 5 |

The test cases are generated so that there will be an answer.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [1,2,5,9], threshold = 6
12 | Output: 5
13 | Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. 
14 | If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). 
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: nums = [44,22,33,11,1], threshold = 5
21 | Output: 44
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • 1 <= nums.length <= 5 * 104
  • 29 |
  • 1 <= nums[i] <= 106
  • 30 |
  • nums.length <= threshold <= 106
  • 31 |
32 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "gcc", 3 | "C_Cpp_Runner.cppCompilerPath": "g++", 4 | "C_Cpp_Runner.debuggerPath": "gdb", 5 | "C_Cpp_Runner.cStandard": "", 6 | "C_Cpp_Runner.cppStandard": "", 7 | "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat", 8 | "C_Cpp_Runner.useMsvc": false, 9 | "C_Cpp_Runner.warnings": [ 10 | "-Wall", 11 | "-Wextra", 12 | "-Wpedantic", 13 | "-Wshadow", 14 | "-Wformat=2", 15 | "-Wcast-align", 16 | "-Wconversion", 17 | "-Wsign-conversion", 18 | "-Wnull-dereference" 19 | ], 20 | "C_Cpp_Runner.msvcWarnings": [ 21 | "/W4", 22 | "/permissive-", 23 | "/w14242", 24 | "/w14287", 25 | "/w14296", 26 | "/w14311", 27 | "/w14826", 28 | "/w44062", 29 | "/w44242", 30 | "/w14905", 31 | "/w14906", 32 | "/w14263", 33 | "/w44265", 34 | "/w14928" 35 | ], 36 | "C_Cpp_Runner.enableWarnings": true, 37 | "C_Cpp_Runner.warningsAsError": false, 38 | "C_Cpp_Runner.compilerArgs": [], 39 | "C_Cpp_Runner.linkerArgs": [], 40 | "C_Cpp_Runner.includePaths": [], 41 | "C_Cpp_Runner.includeSearch": [ 42 | "*", 43 | "**/*" 44 | ], 45 | "C_Cpp_Runner.excludeSearch": [ 46 | "**/build", 47 | "**/build/**", 48 | "**/.*", 49 | "**/.*/**", 50 | "**/.vscode", 51 | "**/.vscode/**" 52 | ], 53 | "C_Cpp_Runner.useAddressSanitizer": false, 54 | "C_Cpp_Runner.useUndefinedSanitizer": false, 55 | "C_Cpp_Runner.useLeakSanitizer": false, 56 | "C_Cpp_Runner.showCompilationTime": false, 57 | "C_Cpp_Runner.useLinkTimeOptimization": false, 58 | "C_Cpp_Runner.msvcSecureNoWarnings": false 59 | } -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0001-two-sum/README.md: -------------------------------------------------------------------------------- 1 |

1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

2 | 3 |

You may assume that each input would have exactly one solution, and you may not use the same element twice.

4 | 5 |

You can return the answer in any order.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [2,7,11,15], target = 9
12 | Output: [0,1]
13 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: nums = [3,2,4], target = 6
20 | Output: [1,2]
21 | 
22 | 23 |

Example 3:

24 | 25 |
26 | Input: nums = [3,3], target = 6
27 | Output: [0,1]
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 2 <= nums.length <= 104
  • 35 |
  • -109 <= nums[i] <= 109
  • 36 |
  • -109 <= target <= 109
  • 37 |
  • Only one valid answer exists.
  • 38 |
39 | 40 |

 

41 | Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1950-sign-of-the-product-of-an-array/README.md: -------------------------------------------------------------------------------- 1 |

1950. Sign of the Product of an Array

Easy


Implement a function signFunc(x) that returns:

2 | 3 |
    4 |
  • 1 if x is positive.
  • 5 |
  • -1 if x is negative.
  • 6 |
  • 0 if x is equal to 0.
  • 7 |
8 | 9 |

You are given an integer array nums. Let product be the product of all values in the array nums.

10 | 11 |

Return signFunc(product).

12 | 13 |

 

14 |

Example 1:

15 | 16 |
17 | Input: nums = [-1,-2,-3,-4,3,2,1]
18 | Output: 1
19 | Explanation: The product of all values in the array is 144, and signFunc(144) = 1
20 | 
21 | 22 |

Example 2:

23 | 24 |
25 | Input: nums = [1,5,0,2,-3]
26 | Output: 0
27 | Explanation: The product of all values in the array is 0, and signFunc(0) = 0
28 | 
29 | 30 |

Example 3:

31 | 32 |
33 | Input: nums = [-1,1,-1,1,-1]
34 | Output: -1
35 | Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
36 | 
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= nums.length <= 1000
  • 43 |
  • -100 <= nums[i] <= 100
  • 44 |
45 | -------------------------------------------------------------------------------- /0907-koko-eating-bananas/README.md: -------------------------------------------------------------------------------- 1 |

907. Koko Eating Bananas

Medium


Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

2 | 3 |

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

4 | 5 |

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

6 | 7 |

Return the minimum integer k such that she can eat all the bananas within h hours.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: piles = [3,6,7,11], h = 8
14 | Output: 4
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: piles = [30,11,23,4,20], h = 5
21 | Output: 30
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: piles = [30,11,23,4,20], h = 6
28 | Output: 23
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= piles.length <= 104
  • 36 |
  • piles.length <= h <= 109
  • 37 |
  • 1 <= piles[i] <= 109
  • 38 |
39 | -------------------------------------------------------------------------------- /03_Arrays/01_Easy_problems/08_linear_search.md: -------------------------------------------------------------------------------- 1 | # ✅ Linear Search in C 2 | 3 | **Problem Statement:** Given an array and an element `num`, the task is to find if `num` is present in the given array or not. If present, print the index of the element, otherwise print -1. 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Given an array of size `N` and an element `num`, determine if `num` exists in the array and return its index. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | ``` 17 | Input: arr[] = {1, 2, 3, 4, 5}, num = 3 18 | Output: 2 19 | Explanation: 3 is present at the 2nd index 20 | ``` 21 | 22 | ### Example 2: 23 | ``` 24 | Input: arr[] = {5, 4, 3, 2, 1}, num = 5 25 | Output: 0 26 | Explanation: 5 is present at the 0th index 27 | ``` 28 | 29 | --- 30 | 31 | ## 💡 Approach 32 | 33 | **Algorithm:** 34 | 1. Traverse through each element of the array 35 | 2. Compare each element with the target value `num` 36 | 3. If a match is found, return the current index 37 | 4. If no match is found after traversing the entire array, return -1 38 | 39 | #### Code (C) 40 | ```c 41 | #include 42 | 43 | int search(int arr[], int n, int num) { 44 | int i; 45 | for(i = 0; i < n; i++) { 46 | if(arr[i] == num) 47 | return i; 48 | } 49 | return -1; 50 | } 51 | 52 | int main() { 53 | int arr[] = {1, 2, 3, 4, 5}; 54 | int num = 4; 55 | int n = sizeof(arr) / sizeof(arr[0]); 56 | int val = search(arr, n, num); 57 | printf("%d", val); 58 | return 0; 59 | } 60 | ``` 61 | **Output:** 3 62 | 63 | **Time Complexity:** O(n), where n is the length of the array. 64 | 65 | **Space Complexity:** O(1) 66 | 67 | --- 68 | 69 | ## 🙌 Credits 70 | 71 | Special thanks to Subhrajit Das for contributing to this article on TakeUforward. 72 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2432-number-of-zero-filled-subarrays/README.md: -------------------------------------------------------------------------------- 1 |

2432. Number of Zero-Filled Subarrays

Medium


Given an integer array nums, return the number of subarrays filled with 0.

2 | 3 |

A subarray is a contiguous non-empty sequence of elements within an array.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [1,3,0,0,2,0,0,4]
10 | Output: 6
11 | Explanation: 
12 | There are 4 occurrences of [0] as a subarray.
13 | There are 2 occurrences of [0,0] as a subarray.
14 | There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
15 | 16 |

Example 2:

17 | 18 |
19 | Input: nums = [0,0,0,2,0,0]
20 | Output: 9
21 | Explanation:
22 | There are 5 occurrences of [0] as a subarray.
23 | There are 3 occurrences of [0,0] as a subarray.
24 | There is 1 occurrence of [0,0,0] as a subarray.
25 | There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
26 | 
27 | 28 |

Example 3:

29 | 30 |
31 | Input: nums = [2,10,2019]
32 | Output: 0
33 | Explanation: There is no subarray filled with 0. Therefore, we return 0.
34 | 
35 | 36 |

 

37 |

Constraints:

38 | 39 |
    40 |
  • 1 <= nums.length <= 105
  • 41 |
  • -109 <= nums[i] <= 109
  • 42 |
43 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2882-ways-to-express-an-integer-as-sum-of-powers/README.md: -------------------------------------------------------------------------------- 1 |

2882. Ways to Express an Integer as Sum of Powers

Medium


Given two positive integers n and x.

2 | 3 |

Return the number of ways n can be expressed as the sum of the xth power of unique positive integers, in other words, the number of sets of unique integers [n1, n2, ..., nk] where n = n1x + n2x + ... + nkx.

4 | 5 |

Since the result can be very large, return it modulo 109 + 7.

6 | 7 |

For example, if n = 160 and x = 3, one way to express n is n = 23 + 33 + 53.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: n = 10, x = 2
14 | Output: 1
15 | Explanation: We can express n as the following: n = 32 + 12 = 10.
16 | It can be shown that it is the only way to express 10 as the sum of the 2nd power of unique integers.
17 | 
18 | 19 |

Example 2:

20 | 21 |
22 | Input: n = 4, x = 1
23 | Output: 2
24 | Explanation: We can express n in the following ways:
25 | - n = 41 = 4.
26 | - n = 31 + 11 = 4.
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 1 <= n <= 300
  • 34 |
  • 1 <= x <= 5
  • 35 |
36 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2575-minimum-cuts-to-divide-a-circle/README.md: -------------------------------------------------------------------------------- 1 |

2575. Minimum Cuts to Divide a Circle

Easy


A valid cut in a circle can be:

2 | 3 |
    4 |
  • A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or
  • 5 |
  • A cut that is represented by a straight line that touches one point on the edge of the circle and its center.
  • 6 |
7 | 8 |

Some valid and invalid cuts are shown in the figures below.

9 | 10 |

Given the integer n, return the minimum number of cuts needed to divide a circle into n equal slices.

11 | 12 |

 

13 |

Example 1:

14 | 15 |
16 | Input: n = 4
17 | Output: 2
18 | Explanation: 
19 | The above figure shows how cutting the circle twice through the middle divides it into 4 equal slices.
20 | 
21 | 22 |

Example 2:

23 | 24 |
25 | Input: n = 3
26 | Output: 3
27 | Explanation:
28 | At least 3 cuts are needed to divide the circle into 3 equal slices. 
29 | It can be shown that less than 3 cuts cannot result in 3 slices of equal size and shape.
30 | Also note that the first cut will not divide the circle into distinct parts.
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • 1 <= n <= 100
  • 38 |
39 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/02_right_angled_triangle.md: -------------------------------------------------------------------------------- 1 | # 🔺 Pattern-2: Right-Angled Triangle Pattern – Striver’s A2Z DSA Sheet 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print the following **right-angled triangle star pattern**: 8 | 9 | ### ✅ Examples 10 | 11 | #### Example 1: 12 | **Input:** `N = 3` 13 | **Output:** 14 | ``` 15 | * 16 | * * 17 | * * * 18 | ``` 19 | 20 | #### Example 2: 21 | **Input:** `N = 6` 22 | **Output:** 23 | ``` 24 | * 25 | * * 26 | * * * 27 | * * * * 28 | * * * * * 29 | * * * * * * 30 | ``` 31 | 32 | --- 33 | 34 | ## 🔍 Approach 35 | 36 | To solve any pattern-based problem, remember the **4 key rules**: 37 | 38 | 1. **Outer loop** → Number of **rows** → Run from `0 to N-1` 39 | 2. **Inner loop** → Number of **columns per row** 40 | - For this right-angled triangle: inner loop runs from `0 to i` (row index). 41 | 3. **What to print:** We print `'* '` inside the inner loop. 42 | 4. Observe the **symmetry or relation** between rows and columns. 43 | 44 | In this specific pattern: 45 | - Each row prints as many `*` as its row number (1-based). 46 | - So row 1 prints 1 star, row 2 prints 2, etc., up to `N` rows. 47 | 48 | --- 49 | 50 | ## ✅ Code (C++) 51 | 52 | ```cpp 53 | #include 54 | using namespace std; 55 | 56 | void pattern2(int N) { 57 | // Outer loop for rows 58 | for (int i = 0; i < N; i++) { 59 | // Inner loop for columns → number of stars = row number (i+1) 60 | for (int j = 0; j <= i; j++) { 61 | cout << "* "; 62 | } 63 | cout << endl; // Move to next line after each row 64 | } 65 | } 66 | 67 | int main() { 68 | int N = 5; // You can take input from the user too 69 | pattern2(N); 70 | return 0; 71 | } 72 | ``` 73 | 74 | --- 75 | 76 | ## 🖥️ Output (When N = 5) 77 | 78 | ``` 79 | * 80 | * * 81 | * * * 82 | * * * * 83 | * * * * * 84 | ``` 85 | 86 | --- 87 | 88 | ## 🙌 Credits 89 | 90 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 91 | 92 | --- 93 | -------------------------------------------------------------------------------- /0033-search-in-rotated-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

33. Search in Rotated Sorted Array

Medium


There is an integer array nums sorted in ascending order (with distinct values).

2 | 3 |

Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left rotated by 3 indices and become [4,5,6,7,0,1,2].

4 | 5 |

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

6 | 7 |

You must write an algorithm with O(log n) runtime complexity.

8 | 9 |

 

10 |

Example 1:

11 |
Input: nums = [4,5,6,7,0,1,2], target = 0
12 | Output: 4
13 | 

Example 2:

14 |
Input: nums = [4,5,6,7,0,1,2], target = 3
15 | Output: -1
16 | 

Example 3:

17 |
Input: nums = [1], target = 0
18 | Output: -1
19 | 
20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 5000
  • 25 |
  • -104 <= nums[i] <= 104
  • 26 |
  • All values of nums are unique.
  • 27 |
  • nums is an ascending array that is possibly rotated.
  • 28 |
  • -104 <= target <= 104
  • 29 |
30 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0679-24-game/README.md: -------------------------------------------------------------------------------- 1 |

679. 24 Game

Hard


You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.

2 | 3 |

You are restricted with the following rules:

4 | 5 |
    6 |
  • The division operator '/' represents real division, not integer division. 7 | 8 |
      9 |
    • For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.
    • 10 |
    11 |
  • 12 |
  • Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. 13 |
      14 |
    • For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed.
    • 15 |
    16 |
  • 17 |
  • You cannot concatenate numbers together 18 |
      19 |
    • For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid.
    • 20 |
    21 |
  • 22 |
23 | 24 |

Return true if you can get such expression that evaluates to 24, and false otherwise.

25 | 26 |

 

27 |

Example 1:

28 | 29 |
30 | Input: cards = [4,1,8,7]
31 | Output: true
32 | Explanation: (8-4) * (7-1) = 24
33 | 
34 | 35 |

Example 2:

36 | 37 |
38 | Input: cards = [1,2,1,2]
39 | Output: false
40 | 
41 | 42 |

 

43 |

Constraints:

44 | 45 |
    46 |
  • cards.length == 4
  • 47 |
  • 1 <= cards[i] <= 9
  • 48 |
49 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2346-largest-3-same-digit-number-in-string/README.md: -------------------------------------------------------------------------------- 1 |

2346. Largest 3-Same-Digit Number in String

Easy


You are given a string num representing a large integer. An integer is good if it meets the following conditions:

2 | 3 |
    4 |
  • It is a substring of num with length 3.
  • 5 |
  • It consists of only one unique digit.
  • 6 |
7 | 8 |

Return the maximum good integer as a string or an empty string "" if no such integer exists.

9 | 10 |

Note:

11 | 12 |
    13 |
  • A substring is a contiguous sequence of characters within a string.
  • 14 |
  • There may be leading zeroes in num or a good integer.
  • 15 |
16 | 17 |

 

18 |

Example 1:

19 | 20 |
21 | Input: num = "6777133339"
22 | Output: "777"
23 | Explanation: There are two distinct good integers: "777" and "333".
24 | "777" is the largest, so we return "777".
25 | 
26 | 27 |

Example 2:

28 | 29 |
30 | Input: num = "2300019"
31 | Output: "000"
32 | Explanation: "000" is the only good integer.
33 | 
34 | 35 |

Example 3:

36 | 37 |
38 | Input: num = "42352338"
39 | Output: ""
40 | Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
41 | 
42 | 43 |

 

44 |

Constraints:

45 | 46 |
    47 |
  • 3 <= num.length <= 1000
  • 48 |
  • num only consists of digits.
  • 49 |
50 | -------------------------------------------------------------------------------- /0081-search-in-rotated-sorted-array-ii/README.md: -------------------------------------------------------------------------------- 1 |

81. Search in Rotated Sorted Array II

Medium


There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

2 | 3 |

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

4 | 5 |

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

6 | 7 |

You must decrease the overall operation steps as much as possible.

8 | 9 |

 

10 |

Example 1:

11 |
Input: nums = [2,5,6,0,0,1,2], target = 0
12 | Output: true
13 | 

Example 2:

14 |
Input: nums = [2,5,6,0,0,1,2], target = 3
15 | Output: false
16 | 
17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • 1 <= nums.length <= 5000
  • 22 |
  • -104 <= nums[i] <= 104
  • 23 |
  • nums is guaranteed to be rotated at some pivot.
  • 24 |
  • -104 <= target <= 104
  • 25 |
26 | 27 |

 

28 |

Follow up: This problem is similar to Search in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?

29 | -------------------------------------------------------------------------------- /1056-capacity-to-ship-packages-within-d-days/README.md: -------------------------------------------------------------------------------- 1 |

1056. Capacity To Ship Packages Within D Days

Medium


A conveyor belt has packages that must be shipped from one port to another within days days.

2 | 3 |

The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

4 | 5 |

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
12 | Output: 15
13 | Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
14 | 1st day: 1, 2, 3, 4, 5
15 | 2nd day: 6, 7
16 | 3rd day: 8
17 | 4th day: 9
18 | 5th day: 10
19 | 
20 | Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
21 | 
22 | 23 |

Example 2:

24 | 25 |
26 | Input: weights = [3,2,2,4,1,4], days = 3
27 | Output: 6
28 | Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
29 | 1st day: 3, 2
30 | 2nd day: 2, 4
31 | 3rd day: 1, 4
32 | 
33 | 34 |

Example 3:

35 | 36 |
37 | Input: weights = [1,2,3,1,1], days = 4
38 | Output: 3
39 | Explanation:
40 | 1st day: 1
41 | 2nd day: 2
42 | 3rd day: 3
43 | 4th day: 1, 1
44 | 
45 | 46 |

 

47 |

Constraints:

48 | 49 |
    50 |
  • 1 <= days <= weights.length <= 5 * 104
  • 51 |
  • 1 <= weights[i] <= 500
  • 52 |
53 | -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

153. Find Minimum in Rotated Sorted Array

Medium


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

2 | 3 |
    4 |
  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • 5 |
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
  • 6 |
7 | 8 |

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

9 | 10 |

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

11 | 12 |

You must write an algorithm that runs in O(log n) time.

13 | 14 |

 

15 |

Example 1:

16 | 17 |
18 | Input: nums = [3,4,5,1,2]
19 | Output: 1
20 | Explanation: The original array was [1,2,3,4,5] rotated 3 times.
21 | 
22 | 23 |

Example 2:

24 | 25 |
26 | Input: nums = [4,5,6,7,0,1,2]
27 | Output: 0
28 | Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
29 | 
30 | 31 |

Example 3:

32 | 33 |
34 | Input: nums = [11,13,15,17]
35 | Output: 11
36 | Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 
37 | 
38 | 39 |

 

40 |

Constraints:

41 | 42 |
    43 |
  • n == nums.length
  • 44 |
  • 1 <= n <= 5000
  • 45 |
  • -5000 <= nums[i] <= 5000
  • 46 |
  • All the integers of nums are unique.
  • 47 |
  • nums is sorted and rotated between 1 and n times.
  • 48 |
49 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2271-rearrange-array-elements-by-sign/README.md: -------------------------------------------------------------------------------- 1 |

2271. Rearrange Array Elements by Sign

Medium


You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

2 | 3 |

You should return the array of nums such that the the array follows the given conditions:

4 | 5 |
    6 |
  1. Every consecutive pair of integers have opposite signs.
  2. 7 |
  3. For all integers with the same sign, the order in which they were present in nums is preserved.
  4. 8 |
  5. The rearranged array begins with a positive integer.
  6. 9 |
10 | 11 |

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

12 | 13 |

 

14 |

Example 1:

15 | 16 |
17 | Input: nums = [3,1,-2,-5,2,-4]
18 | Output: [3,-2,1,-5,2,-4]
19 | Explanation:
20 | The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
21 | The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
22 | Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  
23 | 
24 | 25 |

Example 2:

26 | 27 |
28 | Input: nums = [-1,1]
29 | Output: [1,-1]
30 | Explanation:
31 | 1 is the only positive integer and -1 the only negative integer in nums.
32 | So nums is rearranged to [1,-1].
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 2 <= nums.length <= 2 * 105
  • 40 |
  • nums.length is even
  • 41 |
  • 1 <= |nums[i]| <= 105
  • 42 |
  • nums consists of equal number of positive and negative integers.
  • 43 |
44 | 45 |

 

46 | It is not required to do the modifications in-place. -------------------------------------------------------------------------------- /Dsa_leetcode_problems/4008-restore-finishing-order/README.md: -------------------------------------------------------------------------------- 1 |

4008. Restore Finishing Order

Easy


You are given an integer array order of length n and an integer array friends.

2 | 3 |
    4 |
  • order contains every integer from 1 to n exactly once, representing the IDs of the participants of a race in their finishing order.
  • 5 |
  • friends contains the IDs of your friends in the race sorted in strictly increasing order. Each ID in friends is guaranteed to appear in the order array.
  • 6 |
7 | 8 |

Return an array containing your friends' IDs in their finishing order.

9 | 10 |

 

11 |

Example 1:

12 | 13 |
14 |

Input: order = [3,1,2,5,4], friends = [1,3,4]

15 | 16 |

Output: [3,1,4]

17 | 18 |

Explanation:

19 | 20 |

The finishing order is [3, 1, 2, 5, 4]. Therefore, the finishing order of your friends is [3, 1, 4].

21 |
22 | 23 |

Example 2:

24 | 25 |
26 |

Input: order = [1,4,5,3,2], friends = [2,5]

27 | 28 |

Output: [5,2]

29 | 30 |

Explanation:

31 | 32 |

The finishing order is [1, 4, 5, 3, 2]. Therefore, the finishing order of your friends is [5, 2].

33 |
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 1 <= n == order.length <= 100
  • 40 |
  • order contains every integer from 1 to n exactly once
  • 41 |
  • 1 <= friends.length <= min(8, n)
  • 42 |
  • 1 <= friends[i] <= n
  • 43 |
  • friends is strictly increasing
  • 44 |
45 | -------------------------------------------------------------------------------- /03_Arrays/01_Easy_problems/11_max_consecutive_ones.md: -------------------------------------------------------------------------------- 1 | # ✅ Count Maximum Consecutive One's in the Array 2 | 3 | **Problem Statement:** Given an array that contains only 1 and 0, return the count of maximum consecutive ones in the array. 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Given a binary array (containing only 0s and 1s), find the maximum number of consecutive 1s. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | ``` 17 | Input: array[] = {1, 1, 0, 1, 1, 1} 18 | Output: 3 19 | Explanation: There are two consecutive 1's and three consecutive 1's in the array out of which maximum is 3. 20 | ``` 21 | 22 | ### Example 2: 23 | ``` 24 | Input: array[] = {1, 0, 1, 1, 0, 1} 25 | Output: 2 26 | Explanation: There are two consecutive 1's in the array. 27 | ``` 28 | 29 | --- 30 | 31 | ## 💡 Approach 32 | 33 | **Algorithm:** 34 | 1. Maintain a variable `count` that tracks the current number of consecutive 1's 35 | 2. Maintain a variable `max_count` that stores the maximum consecutive 1's found so far 36 | 3. Traverse through the array: 37 | - If current element is 1, increment `count` 38 | - If current element is 0, reset `count` to 0 39 | - Update `max_count` with the maximum value between current `max_count` and `count` 40 | 41 | #### Code (C++) 42 | ```cpp 43 | #include 44 | using namespace std; 45 | 46 | class Solution { 47 | public: 48 | int findMaxConsecutiveOnes(vector& nums) { 49 | int cnt = 0; 50 | int maxi = 0; 51 | for (int i = 0; i < nums.size(); i++) { 52 | if (nums[i] == 1) { 53 | cnt++; 54 | } else { 55 | cnt = 0; 56 | } 57 | maxi = max(maxi, cnt); 58 | } 59 | return maxi; 60 | } 61 | }; 62 | 63 | int main() { 64 | vector nums = {1, 1, 0, 1, 1, 1}; 65 | Solution obj; 66 | int ans = obj.findMaxConsecutiveOnes(nums); 67 | cout << "The maximum consecutive 1's are: " << ans; 68 | return 0; 69 | } 70 | ``` 71 | **Output:** The maximum consecutive 1's are: 3 72 | 73 | **Time Complexity:** O(N) since the solution involves only a single pass. 74 | 75 | **Space Complexity:** O(1) because no extra space is used. 76 | 77 | --- 78 | 79 | ## 🙌 Credits 80 | 81 | Special thanks to Somparna Chakrabarti and Sudip Ghosh for contributing to this article on TakeUforward. 82 | -------------------------------------------------------------------------------- /0141-linked-list-cycle/README.md: -------------------------------------------------------------------------------- 1 |

141. Linked List Cycle

Easy


Given head, the head of a linked list, determine if the linked list has a cycle in it.

2 | 3 |

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

4 | 5 |

Return true if there is a cycle in the linked list. Otherwise, return false.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: head = [3,2,0,-4], pos = 1
12 | Output: true
13 | Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: head = [1,2], pos = 0
20 | Output: true
21 | Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: head = [1], pos = -1
28 | Output: false
29 | Explanation: There is no cycle in the linked list.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • The number of the nodes in the list is in the range [0, 104].
  • 37 |
  • -105 <= Node.val <= 105
  • 38 |
  • pos is -1 or a valid index in the linked-list.
  • 39 |
40 | 41 |

 

42 |

Follow up: Can you solve it using O(1) (i.e. constant) memory?

43 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/2529-range-product-queries-of-powers/README.md: -------------------------------------------------------------------------------- 1 |

2529. Range Product Queries of Powers

Medium


Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array.

2 | 3 |

You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Each queries[i] represents a query where you have to find the product of all powers[j] with lefti <= j <= righti.

4 | 5 |

Return an array answers, equal in length to queries, where answers[i] is the answer to the ith query. Since the answer to the ith query may be too large, each answers[i] should be returned modulo 109 + 7.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: n = 15, queries = [[0,1],[2,2],[0,3]]
12 | Output: [2,4,64]
13 | Explanation:
14 | For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.
15 | Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.
16 | Answer to 2nd query: powers[2] = 4.
17 | Answer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.
18 | Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.
19 | 
20 | 21 |

Example 2:

22 | 23 |
24 | Input: n = 2, queries = [[0,0]]
25 | Output: [2]
26 | Explanation:
27 | For n = 2, powers = [2].
28 | The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= n <= 109
  • 36 |
  • 1 <= queries.length <= 105
  • 37 |
  • 0 <= starti <= endi < powers.length
  • 38 |
39 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/03_right_angled_number.md: -------------------------------------------------------------------------------- 1 | # 🔺 Pattern-3: Right-Angled Number Pyramid – Striver’s A2Z DSA Sheet 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print the following **right-angled number pyramid pattern**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | 1 18 | 1 2 19 | 1 2 3 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | 1 27 | 1 2 28 | 1 2 3 29 | 1 2 3 4 30 | 1 2 3 4 5 31 | 1 2 3 4 5 6 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | There are **4 general rules** for solving a pattern-based problem: 39 | 40 | 1. **Outer Loop** – Controls the number of rows (`N` times). 41 | 2. **Inner Loop** – Controls the number of columns (depends on the row number). 42 | 3. **Print Statement** – Decide what to print (numbers in this case). 43 | 4. **Line Break** – After each row, print a new line. 44 | 45 | ### 🧠 Pattern Logic: 46 | 47 | - For every row `i` (1-based index), print numbers from `1` to `i`. 48 | - Example: In row 4, print: `1 2 3 4` 49 | - The pattern forms an upright right-angled triangle of numbers. 50 | 51 | --- 52 | 53 | ## ✅ Code (C++) 54 | 55 | ```cpp 56 | #include 57 | using namespace std; 58 | 59 | void pattern3(int N) { 60 | // Outer loop for rows 61 | for (int i = 1; i <= N; i++) { 62 | // Inner loop for numbers in each row 63 | for (int j = 1; j <= i; j++) { 64 | cout << j << " "; 65 | } 66 | cout << endl; // Line break after each row 67 | } 68 | } 69 | 70 | int main() { 71 | int N = 5; // You can take input from the user as well 72 | pattern3(N); 73 | return 0; 74 | } 75 | ``` 76 | 77 | --- 78 | 79 | ## 🖥️ Output (When N = 5) 80 | 81 | ``` 82 | 1 83 | 1 2 84 | 1 2 3 85 | 1 2 3 4 86 | 1 2 3 4 5 87 | ``` 88 | 89 | --- 90 | 91 | ## 📌 Additional Notes 92 | 93 | - This pattern is similar to **Pattern-2**, but instead of stars, it prints incrementing numbers starting from 1 up to the row index. 94 | - It helps in practicing **nested loops** and **loop control logic**. 95 | 96 | --- 97 | 98 | ## 🙌 Credits 99 | 100 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 101 | 102 | --- 103 | 104 | ## 🔗 Related Links 105 | 106 | - [DSA Sheet – Striver's A2Z](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 107 | - [Explore Patterns](https://takeuforward.org/patterns/) 108 | 109 | --- 110 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/01_rectangular_star.md: -------------------------------------------------------------------------------- 1 | # 🌟 04. Pattern-1: Rectangular Star Pattern 2 | 3 | ## 📝 Problem Statement: 4 | Given an integer `N`, print the following **N x N** star pattern. 5 | 6 | --- 7 | 8 | ## 📥 Input: 9 | 10 | - An integer `N` (number of rows and columns) 11 | 12 | --- 13 | 14 | ## 📤 Output: 15 | 16 | A rectangular (square) pattern with `N` rows and `N` columns where each element is a `*`. 17 | 18 | --- 19 | 20 | ## ✨ Example 1: 21 | 22 | **Input:** `N = 3` 23 | **Output:** 24 | ``` 25 | * * * 26 | * * * 27 | * * * 28 | ``` 29 | 30 | --- 31 | 32 | ## ✨ Example 2: 33 | 34 | **Input:** `N = 6` 35 | **Output:** 36 | ``` 37 | * * * * * * 38 | * * * * * * 39 | * * * * * * 40 | * * * * * * 41 | * * * * * * 42 | * * * * * * 43 | ``` 44 | 45 | --- 46 | 47 | ## 🔍 Approach: 48 | 49 | There are **4 general rules** for solving pattern-based problems: 50 | 51 | 1. **Use nested loops:** 52 | - The **outer loop** runs for the number of **rows (N)**. 53 | - The **inner loop** runs for the number of **columns (N)** in each row. 54 | 55 | 2. **Print the symbol (`*`) inside the inner loop.** 56 | 57 | 3. **Use `cout << endl;` to move to the next row after printing each line.** 58 | 59 | 4. **Look for symmetry:** 60 | This is a square pattern, so rows = columns. 61 | 62 | --- 63 | 64 | ## 💻 Code (C++): 65 | 66 | ```cpp 67 | #include 68 | using namespace std; 69 | 70 | void pattern1(int N) 71 | { 72 | // Outer loop for rows 73 | for (int i = 0; i < N; i++) 74 | { 75 | // Inner loop for columns 76 | for (int j = 0; j < N; j++) 77 | { 78 | cout << "* "; 79 | } 80 | 81 | // Move to the next line after printing each row 82 | cout << endl; 83 | } 84 | } 85 | 86 | int main() 87 | { 88 | int N = 5; // You can also take user input using cin 89 | pattern1(N); 90 | return 0; 91 | } 92 | ``` 93 | 94 | --- 95 | 96 | ## 🖥️ Output (for N = 5): 97 | 98 | ``` 99 | * * * * * 100 | * * * * * 101 | * * * * * 102 | * * * * * 103 | * * * * * 104 | ``` 105 | 106 | --- 107 | 108 | ## 🧠 Key Takeaways: 109 | 110 | - This is a basic square star pattern. 111 | - Learn how to use **nested loops** effectively. 112 | - Helps build intuition for more complex patterns (triangles, pyramids, etc.) 113 | 114 | --- 115 | 116 | > 🎉 Special thanks to **Priyanshi Goel** for contributing to this article on takeUforward. 117 | 118 | 📚 _Want to master patterns and DSA step-by-step?_ 119 | 👉 [Striver’s A2Z DSA Sheet](https://takeuforward.org/dsa/strivers-a2z-dsa-course-sheet-2/) 120 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/05_inverted_right_pyramid.md: -------------------------------------------------------------------------------- 1 | # 🔻 Pattern-5: Inverted Right Pyramid 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print the following **inverted right-angled star pattern**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | * * * 18 | * * 19 | * 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | * * * * * * 27 | * * * * * 28 | * * * * 29 | * * * 30 | * * 31 | * 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | To solve pattern-based problems, remember these **4 golden rules**: 39 | 40 | 1. **Outer loop** → Runs for the number of rows (here `N` rows). 41 | 2. **Inner loop** → Determines the number of columns → Here, `(N - current_row_index)`. 42 | 3. **What to print** → `'* '` inside the inner loop. 43 | 4. **Line break** → After each row is printed. 44 | 45 | ### 🧠 Key Idea: 46 | - Row `0` → `N` stars. 47 | - Row `1` → `N - 1` stars. 48 | - Continue until the last row has `1` star. 49 | 50 | --- 51 | 52 | ## ✅ Code (C++) 53 | 54 | ```cpp 55 | #include 56 | using namespace std; 57 | 58 | void pattern5(int N) { 59 | // Outer loop for rows 60 | for (int i = 0; i < N; i++) { 61 | // Inner loop for decreasing number of stars 62 | for (int j = N; j > i; j--) { 63 | cout << "* "; 64 | } 65 | cout << endl; // Move to the next line 66 | } 67 | } 68 | 69 | int main() { 70 | int N = 5; // Example input 71 | pattern5(N); 72 | return 0; 73 | } 74 | ``` 75 | 76 | --- 77 | 78 | ## 🖥️ Output (When N = 5) 79 | 80 | ``` 81 | * * * * * 82 | * * * * 83 | * * * 84 | * * 85 | * 86 | ``` 87 | 88 | --- 89 | 90 | ## 🖼️ Pattern Illustration 91 | 92 | > Save an image named `pattern5.png` inside the `images/` folder in your repository. 93 | 94 | ```markdown 95 | ![Pattern 5 – Inverted Right Pyramid](images/pattern5.png) 96 | ``` 97 | 98 | --- 99 | 100 | ## 📌 Notes 101 | 102 | - Similar to **Pattern-2**, but stars **decrease** each row instead of increasing. 103 | - Good practice for **nested loops** and reverse iteration. 104 | 105 | --- 106 | 107 | ## 🙌 Credits 108 | 109 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 110 | 111 | --- 112 | 113 | ## 🔗 Related Links 114 | 115 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 116 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 117 | 118 | --- 119 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/1878-check-if-array-is-sorted-and-rotated/README.md: -------------------------------------------------------------------------------- 1 |

1878. Check if Array Is Sorted and Rotated

Easy


Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

2 | 3 |

There may be duplicates in the original array.

4 | 5 |

Note: An array A rotated by x positions results in an array B of the same length such that B[i] == A[(i+x) % A.length] for every valid index i.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [3,4,5,1,2]
12 | Output: true
13 | Explanation: [1,2,3,4,5] is the original sorted array.
14 | You can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2].
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: nums = [2,1,3,4]
21 | Output: false
22 | Explanation: There is no sorted array once rotated that can make nums.
23 | 
24 | 25 |

Example 3:

26 | 27 |
28 | Input: nums = [1,2,3]
29 | Output: true
30 | Explanation: [1,2,3] is the original sorted array.
31 | You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
32 | 
33 | 34 |
35 |
36 |
 
37 | 38 |
39 |
40 |
 
41 | 42 |
43 |

 

44 | 45 |

 

46 |
47 |
48 |
49 |
50 |
51 | 52 |

 

53 |

Constraints:

54 | 55 |
    56 |
  • 1 <= nums.length <= 100
  • 57 |
  • 1 <= nums[i] <= 100
  • 58 |
59 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/06_inverted_numbered_right_pyramid.md: -------------------------------------------------------------------------------- 1 | # 🔽 Pattern-6: Inverted Numbered Right Pyramid 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print the following **inverted right-angled number pyramid**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | 1 2 3 18 | 1 2 19 | 1 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | 1 2 3 4 5 6 27 | 1 2 3 4 5 28 | 1 2 3 4 29 | 1 2 3 30 | 1 2 31 | 1 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | To solve any pattern-based problem, follow the **4 golden rules**: 39 | 40 | 1. **Outer loop** → Runs `N` times (for each row). 41 | 2. **Inner loop** → Determines the number of columns → Here, `(N - current_row_index)`. 42 | 3. **What to print** → Numbers from `1` up to `(N - i)` for each row. 43 | 4. **Line break** → After each row. 44 | 45 | ### 🧠 Key Idea: 46 | - Row `0` → Numbers `1` to `N`. 47 | - Row `1` → Numbers `1` to `N - 1`. 48 | - Row `i` → Numbers `1` to `(N - i)`. 49 | 50 | --- 51 | 52 | ## ✅ Code (C++) 53 | 54 | ```cpp 55 | #include 56 | using namespace std; 57 | 58 | void pattern6(int N) { 59 | // Outer loop for rows 60 | for (int i = 0; i < N; i++) { 61 | // Inner loop for printing numbers 62 | for (int j = N; j > i; j--) { 63 | cout << N - j + 1 << " "; 64 | } 65 | cout << endl; // Move to next line 66 | } 67 | } 68 | 69 | int main() { 70 | int N = 5; // Example input 71 | pattern6(N); 72 | return 0; 73 | } 74 | ``` 75 | 76 | --- 77 | 78 | ## 🖥️ Output (When N = 5) 79 | 80 | ``` 81 | 1 2 3 4 5 82 | 1 2 3 4 83 | 1 2 3 84 | 1 2 85 | 1 86 | ``` 87 | 88 | --- 89 | 90 | ## 🖼️ Pattern Illustration 91 | 92 | > Save an image named `pattern6.png` inside the `images/` folder in your repository. 93 | 94 | ```markdown 95 | ![Pattern 6 – Inverted Numbered Right Pyramid](images/pattern6.png) 96 | ``` 97 | 98 | --- 99 | 100 | ## 📌 Notes 101 | 102 | - Similar to **Pattern-5** but instead of stars, numbers are printed in **increasing order starting from 1**. 103 | - Useful for practicing **nested loops** and understanding **row-column relationships**. 104 | 105 | --- 106 | 107 | ## 🙌 Credits 108 | 109 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 110 | 111 | --- 112 | 113 | ## 🔗 Related Links 114 | 115 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 116 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 117 | 118 | --- 119 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/STL_C++/01_Intro _stl.md: -------------------------------------------------------------------------------- 1 | # 📘 C++ STL Tutorial: Most Frequently Used Containers & Algorithms 2 | 3 | ## 📌 What is C++ STL? 4 | 5 | C++ **STL (Standard Template Library)** is a powerful library that provides pre-defined templates, containers, and algorithms. It allows programmers to easily implement common data structures and perform operations efficiently without writing everything from scratch. 6 | 7 | ✅ **Why use STL?** 8 | 9 | * Saves development time 10 | * Provides efficient implementations 11 | * Widely used in **competitive programming** 12 | * Supports reusability and modular programming 13 | 14 | --- 15 | 16 | ## 📂 STL Containers 17 | 18 | ### 🔹 Sequence Containers 19 | 20 | * **Vector** → Dynamic array with fast random access. 21 | * **Deque** → Double-ended queue (insertion/removal from both ends). 22 | * **List** → Doubly linked list. 23 | * **Stack** → LIFO (Last In First Out). 24 | * **Queue** → FIFO (First In First Out). 25 | * **Priority Queue** → Max/Min heap based implementation. 26 | 27 | ### 🔹 Associative Containers 28 | 29 | * **Set** → Stores unique sorted elements. 30 | * **Multiset** → Stores sorted elements (allows duplicates). 31 | * **Unordered Set** → Stores unique elements (no specific order). 32 | * **Unordered Multiset** → Stores duplicate elements (no specific order). 33 | * **Map** → Stores key-value pairs in sorted order (unique keys). 34 | * **Multimap** → Stores key-value pairs (allows duplicate keys). 35 | * **Unordered Map** → Stores key-value pairs (unique keys, no specific order). 36 | * **Unordered Multimap** → Stores key-value pairs (duplicate keys, no specific order). 37 | 38 | --- 39 | 40 | ## ⚡ Commonly Used STL Algorithms 41 | 42 | * **`sort()`** → Sorts a container in ascending order by default. 43 | * **`min_element()`** → Returns the smallest element in a container. 44 | * **`max_element()`** → Returns the largest element in a container. 45 | * **`next_permutation()`** → Rearranges elements into the next lexicographical permutation. 46 | * **`__builtin_popcount()`** → Returns the number of set bits (1s) in an integer. 47 | 48 | --- 49 | 50 | ## 🎥 Video Tutorial 51 | 52 | 👉 *Recommended:* Watch tutorials on YouTube or platforms like GeeksforGeeks & TakeUForward. 53 | 54 | --- 55 | 56 | ## 🎯 Summary 57 | 58 | STL is one of the biggest strengths of C++: 59 | 60 | * Ready-to-use **containers** (vectors, sets, maps, etc.) 61 | * Efficient **algorithms** (sorting, searching, permutations) 62 | * Simplifies **competitive programming & real-world projects** 63 | 64 | --- 65 | 66 | ## 📌 Quick Links 67 | 68 | * [GeeksforGeeks STL Tutorial](https://www.geeksforgeeks.org/the-c-standard-template-library-stl/) 69 | * [TakeUForward STL Guide](https://takeuforward.org/) 70 | 71 | --- 72 | 73 | 🚀 *Mastering STL is essential for every C++ programmer!* 74 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/10_half_diamond_star.md: -------------------------------------------------------------------------------- 1 | # ⭐ Pattern-10: Half Diamond Star Pattern 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print a **half diamond star pattern** (right-aligned). 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | * 18 | ** 19 | *** 20 | ** 21 | * 22 | ``` 23 | 24 | ### Example 2: 25 | **Input:** `N = 6` 26 | **Output:** 27 | ``` 28 | * 29 | ** 30 | *** 31 | **** 32 | ***** 33 | ****** 34 | ***** 35 | **** 36 | *** 37 | ** 38 | * 39 | ``` 40 | 41 | --- 42 | 43 | ## 🔍 Approach 44 | 45 | Follow the **4 golden rules** for pattern printing: 46 | 47 | 1. **Outer loop** → Runs `2*N - 1` times (because the diamond has two halves). 48 | 2. **Inner loop** → 49 | - If row `i ≤ N` → number of stars = `i`. 50 | - If row `i > N` → number of stars = `2*N - i`. 51 | 3. **Line break** after each row. 52 | 4. This is essentially **half of a full diamond** (Pattern-9) printed vertically. 53 | 54 | ### 🧠 Key Idea: 55 | - First half → Increases stars from 1 to `N`. 56 | - Second half → Decreases stars from `N - 1` back to 1. 57 | 58 | --- 59 | 60 | ## ✅ Code (C++) 61 | 62 | ```cpp 63 | #include 64 | using namespace std; 65 | 66 | void pattern10(int N) { 67 | for (int i = 1; i <= 2 * N - 1; i++) { 68 | int stars = i; 69 | if (i > N) stars = 2 * N - i; 70 | for (int j = 1; j <= stars; j++) { 71 | cout << "*"; 72 | } 73 | cout << endl; 74 | } 75 | } 76 | 77 | int main() { 78 | int N = 5; // Example input 79 | pattern10(N); 80 | return 0; 81 | } 82 | ``` 83 | 84 | --- 85 | 86 | ## 🖥️ Output (When N = 5) 87 | 88 | ``` 89 | * 90 | ** 91 | *** 92 | **** 93 | ***** 94 | **** 95 | *** 96 | ** 97 | * 98 | ``` 99 | 100 | --- 101 | 102 | ## 🖼️ Pattern Illustration 103 | 104 | > Save an image named `pattern10.png` inside the `images/` folder in your repository. 105 | 106 | ```markdown 107 | ![Pattern 10 – Half Diamond Star Pattern](images/pattern10.png) 108 | ``` 109 | 110 | --- 111 | 112 | ## 📌 Notes 113 | 114 | - This is **half of Pattern-9 (Diamond Star Pattern)**. 115 | - Good practice for understanding **increment–decrement star logic**. 116 | - Helps in mastering **mirror symmetry**. 117 | 118 | --- 119 | 120 | ## 🙌 Credits 121 | 122 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 123 | 124 | --- 125 | 126 | ## 🔗 Related Links 127 | 128 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 129 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 130 | 131 | --- 132 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/04_right_angled_triangle_prymaid.md: -------------------------------------------------------------------------------- 1 | # 🔺 Pattern-4: Right-Angled Number Pyramid – II (Striver’s A2Z DSA Sheet) 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print the following **right-angled number pyramid** where each row contains the **same number repeated**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | 1 18 | 2 2 19 | 3 3 3 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | 1 27 | 2 2 28 | 3 3 3 29 | 4 4 4 4 30 | 5 5 5 5 5 31 | 6 6 6 6 6 6 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | There are **4 general rules** for solving any pattern-based problem: 39 | 40 | 1. **Outer Loop** → Number of rows → Run from `1 to N`. 41 | 2. **Inner Loop** → Number of columns → Related to the row number. 42 | 3. **Print Statement** → Here, print the **row number** instead of stars or sequence. 43 | 4. **Line Break** → After each row, print a newline. 44 | 45 | ### 🧠 Logic for This Pattern: 46 | 47 | - For each row `i`, print the number `i` exactly `i` times. 48 | - Row 1: `1` 49 | - Row 4: `4 4 4 4` 50 | - Continue until `N` rows. 51 | 52 | --- 53 | 54 | ## ✅ Code (C++) 55 | 56 | ```cpp 57 | #include 58 | using namespace std; 59 | 60 | void pattern4(int N) { 61 | // Outer loop for rows 62 | for (int i = 1; i <= N; i++) { 63 | // Inner loop for columns 64 | for (int j = 1; j <= i; j++) { 65 | cout << i << " "; 66 | } 67 | cout << endl; // New line after each row 68 | } 69 | } 70 | 71 | int main() { 72 | int N = 5; // Example value, can take user input 73 | pattern4(N); 74 | return 0; 75 | } 76 | ``` 77 | 78 | --- 79 | 80 | ## 🖥️ Output (When N = 5) 81 | 82 | ``` 83 | 1 84 | 2 2 85 | 3 3 3 86 | 4 4 4 4 87 | 5 5 5 5 5 88 | ``` 89 | 90 | --- 91 | 92 | ## 🖼️ Pattern Illustration 93 | 94 | > Save an image named `pattern4.png` inside the `images/` folder of your repository. 95 | 96 | ```markdown 97 | ![Pattern 4 – Right-Angled Number Pyramid II](images/pattern4.png) 98 | ``` 99 | 100 | --- 101 | 102 | ## 📌 Notes 103 | 104 | - Similar to **Pattern-2** and **Pattern-3**, but prints **repeated row numbers**. 105 | - Reinforces **nested loops** and controlling the output. 106 | 107 | --- 108 | 109 | ## 🙌 Credits 110 | 111 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 112 | 113 | --- 114 | 115 | ## 🔗 Related Links 116 | 117 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 118 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 119 | 120 | --- 121 | -------------------------------------------------------------------------------- /1605-minimum-number-of-days-to-make-m-bouquets/README.md: -------------------------------------------------------------------------------- 1 |

1605. Minimum Number of Days to Make m Bouquets

Medium


You are given an integer array bloomDay, an integer m and an integer k.

2 | 3 |

You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.

4 | 5 |

The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.

6 | 7 |

Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
14 | Output: 3
15 | Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.
16 | We need 3 bouquets each should contain 1 flower.
17 | After day 1: [x, _, _, _, _]   // we can only make one bouquet.
18 | After day 2: [x, _, _, _, x]   // we can only make two bouquets.
19 | After day 3: [x, _, x, _, x]   // we can make 3 bouquets. The answer is 3.
20 | 
21 | 22 |

Example 2:

23 | 24 |
25 | Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
26 | Output: -1
27 | Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
28 | 
29 | 30 |

Example 3:

31 | 32 |
33 | Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
34 | Output: 12
35 | Explanation: We need 2 bouquets each should have 3 flowers.
36 | Here is the garden after the 7 and 12 days:
37 | After day 7: [x, x, x, x, _, x, x]
38 | We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
39 | After day 12: [x, x, x, x, x, x, x]
40 | It is obvious that we can make two bouquets in different ways.
41 | 
42 | 43 |

 

44 |

Constraints:

45 | 46 |
    47 |
  • bloomDay.length == n
  • 48 |
  • 1 <= n <= 105
  • 49 |
  • 1 <= bloomDay[i] <= 109
  • 50 |
  • 1 <= m <= 106
  • 51 |
  • 1 <= k <= n
  • 52 |
53 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0026-remove-duplicates-from-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

26. Remove Duplicates from Sorted Array

Easy


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 |
    6 |
  • 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.
  • 7 |
  • Return k.
  • 8 |
9 | 10 |

Custom Judge:

11 | 12 |

The judge will test your solution with the following code:

13 | 14 |
15 | int[] nums = [...]; // Input array
16 | int[] expectedNums = [...]; // The expected answer with correct length
17 | 
18 | int k = removeDuplicates(nums); // Calls your implementation
19 | 
20 | assert k == expectedNums.length;
21 | for (int i = 0; i < k; i++) {
22 |     assert nums[i] == expectedNums[i];
23 | }
24 | 
25 | 26 |

If all assertions pass, then your solution will be accepted.

27 | 28 |

 

29 |

Example 1:

30 | 31 |
32 | Input: nums = [1,1,2]
33 | Output: 2, nums = [1,2,_]
34 | Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
35 | It does not matter what you leave beyond the returned k (hence they are underscores).
36 | 
37 | 38 |

Example 2:

39 | 40 |
41 | Input: nums = [0,0,1,1,1,2,2,3,3,4]
42 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
43 | Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
44 | It does not matter what you leave beyond the returned k (hence they are underscores).
45 | 
46 | 47 |

 

48 |

Constraints:

49 | 50 |
    51 |
  • 1 <= nums.length <= 3 * 104
  • 52 |
  • -100 <= nums[i] <= 100
  • 53 |
  • nums is sorted in non-decreasing order.
  • 54 |
55 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/11_binary_number_triangle.md: -------------------------------------------------------------------------------- 1 | # ⭐ Pattern-11: Binary Number Triangle Pattern 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print a **binary number triangle pattern** where `1` and `0` are placed alternately in each row. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | 1 18 | 01 19 | 101 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | 1 27 | 01 28 | 101 29 | 0101 30 | 10101 31 | 010101 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | Follow the **4 golden rules** for pattern printing: 39 | 40 | 1. **Outer loop** → Runs `N` times (for each row). 41 | 2. **Inner loop** → 42 | - The starting value alternates by row: 43 | - If `i` is even → start with `1`. 44 | - If `i` is odd → start with `0`. 45 | - Alternate the number for each column using `start = 1 - start`. 46 | 3. **Line break** after each row. 47 | 4. This pattern is simply alternating binary digits based on row and column index. 48 | 49 | ### 🧠 Key Idea: 50 | - Use a `start` variable to decide the first digit of the row. 51 | - Flip `start` after printing each number. 52 | 53 | --- 54 | 55 | ## ✅ Code (C++) 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void pattern11(int N) { 62 | int start = 1; 63 | for (int i = 0; i < N; i++) { 64 | if (i % 2 == 0) start = 1; // Even row index → start with 1 65 | else start = 0; // Odd row index → start with 0 66 | 67 | for (int j = 0; j <= i; j++) { 68 | cout << start; 69 | start = 1 - start; // Toggle between 1 and 0 70 | } 71 | cout << endl; 72 | } 73 | } 74 | 75 | int main() { 76 | int N = 5; // Example input 77 | pattern11(N); 78 | return 0; 79 | } 80 | ``` 81 | 82 | --- 83 | 84 | ## 🖥️ Output (When N = 5) 85 | 86 | ``` 87 | 1 88 | 01 89 | 101 90 | 0101 91 | 10101 92 | ``` 93 | 94 | --- 95 | 96 | ## 🖼️ Pattern Illustration 97 | 98 | > Save an image named `pattern11.png` inside the `images/` folder in your repository. 99 | 100 | ```markdown 101 | ![Pattern 11 – Binary Number Triangle Pattern](images/pattern11.png) 102 | ``` 103 | 104 | --- 105 | 106 | ## 📌 Notes 107 | 108 | - Alternates `1` and `0` across each row and column. 109 | - Useful for learning **toggle logic** using `start = 1 - start`. 110 | - Demonstrates **row-based initialization**. 111 | 112 | --- 113 | 114 | ## 🙌 Credits 115 | 116 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 117 | 118 | --- 119 | 120 | ## 🔗 Related Links 121 | 122 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 123 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 124 | 125 | --- 126 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/08_ inverted_star_pyramid.md: -------------------------------------------------------------------------------- 1 | # ⭐ Pattern-8: Inverted Star Pyramid 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print an **inverted center-aligned star pyramid**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | ***** 18 | *** 19 | * 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | *********** 27 | ********* 28 | ******* 29 | ***** 30 | *** 31 | * 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | Follow the **4 golden rules** for pattern printing: 39 | 40 | 1. **Outer loop** → Runs `N` times (for each row). 41 | 2. **Inner loops** → 42 | - First loop → Prints **spaces before stars** → `i` spaces. 43 | - Second loop → Prints **stars** → `2*N - (2*i + 1)` stars. 44 | - Third loop → Prints **spaces after stars** → `i` spaces. 45 | 3. **Line break** after each row. 46 | 4. This is essentially **Pattern-7** reversed vertically. 47 | 48 | ### 🧠 Key Idea: 49 | - Row `0` → 0 spaces, `2*N - 1` stars, 0 spaces. 50 | - Row `1` → 1 space, `2*N - 3` stars, 1 space. 51 | - Row `i` → `i` spaces, `(2*N - (2*i + 1))` stars, `i` spaces. 52 | 53 | --- 54 | 55 | ## ✅ Code (C++) 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void pattern8(int N) { 62 | // Outer loop for rows 63 | for (int i = 0; i < N; i++) { 64 | 65 | // Spaces before stars 66 | for (int j = 0; j < i; j++) { 67 | cout << " "; 68 | } 69 | 70 | // Stars 71 | for (int j = 0; j < 2 * N - (2 * i + 1); j++) { 72 | cout << "*"; 73 | } 74 | 75 | // Spaces after stars 76 | for (int j = 0; j < i; j++) { 77 | cout << " "; 78 | } 79 | 80 | // Move to next line 81 | cout << endl; 82 | } 83 | } 84 | 85 | int main() { 86 | int N = 5; // Example input 87 | pattern8(N); 88 | return 0; 89 | } 90 | ``` 91 | 92 | --- 93 | 94 | ## 🖥️ Output (When N = 5) 95 | 96 | ``` 97 | ********* 98 | ******* 99 | ***** 100 | *** 101 | * 102 | ``` 103 | 104 | --- 105 | 106 | ## 🖼️ Pattern Illustration 107 | 108 | > Save an image named `pattern8.png` inside the `images/` folder in your repository. 109 | 110 | ```markdown 111 | ![Pattern 8 – Inverted Star Pyramid](images/pattern8.png) 112 | ``` 113 | 114 | --- 115 | 116 | ## 📌 Notes 117 | 118 | - This is the **reverse** of Pattern-7 (Star Pyramid). 119 | - Practice helps in mastering **space–star alignment**. 120 | - Useful for understanding **mirror symmetry in patterns**. 121 | 122 | --- 123 | 124 | ## 🙌 Credits 125 | 126 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 127 | 128 | --- 129 | 130 | ## 🔗 Related Links 131 | 132 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 133 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 134 | 135 | --- 136 | -------------------------------------------------------------------------------- /Dsa_leetcode_problems/0268-missing-number/README.md: -------------------------------------------------------------------------------- 1 |

268. Missing Number

Easy


Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
7 |

Input: nums = [3,0,1]

8 | 9 |

Output: 2

10 | 11 |

Explanation:

12 | 13 |

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.

14 |
15 | 16 |

Example 2:

17 | 18 |
19 |

Input: nums = [0,1]

20 | 21 |

Output: 2

22 | 23 |

Explanation:

24 | 25 |

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.

26 |
27 | 28 |

Example 3:

29 | 30 |
31 |

Input: nums = [9,6,4,2,3,5,7,0,1]

32 | 33 |

Output: 8

34 | 35 |

Explanation:

36 | 37 |

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.

38 |
39 | 40 |
41 |
42 |
 
43 | 44 |
45 |
46 |
 
47 | 48 |
49 |

 

50 | 51 |

 

52 |
53 |
54 |
55 |
56 |
57 | 58 |

 

59 |

Constraints:

60 | 61 |
    62 |
  • n == nums.length
  • 63 |
  • 1 <= n <= 104
  • 64 |
  • 0 <= nums[i] <= n
  • 65 |
  • All the numbers of nums are unique.
  • 66 |
67 | 68 |

 

69 |

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

70 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/07_star_pyramid.md: -------------------------------------------------------------------------------- 1 | # ⭐ Pattern-7: Star Pyramid 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print a **center-aligned star pyramid**. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | * 18 | *** 19 | ***** 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | * 27 | *** 28 | ***** 29 | ******* 30 | ********* 31 | *********** 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | To solve any pattern-based problem, follow the **4 golden rules**: 39 | 40 | 1. **Outer loop** → Runs `N` times (for each row). 41 | 2. **Inner loops** → 42 | - First loop → Prints **spaces** before stars → `(N - i - 1)` spaces. 43 | - Second loop → Prints **stars** → `(2 * i + 1)` stars. 44 | - Third loop → Prints **spaces** after stars → `(N - i - 1)` spaces. 45 | 3. **Line break** → After each row. 46 | 4. Observe symmetry and alignment. 47 | 48 | ### 🧠 Key Idea: 49 | - Row `0` → `N-1` spaces, `1` star, `N-1` spaces. 50 | - Row `1` → `N-2` spaces, `3` stars, `N-2` spaces. 51 | - Row `i` → `(N - i - 1)` spaces, `(2 * i + 1)` stars, `(N - i - 1)` spaces. 52 | 53 | --- 54 | 55 | ## ✅ Code (C++) 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void pattern7(int N) { 62 | // Outer loop for rows 63 | for (int i = 0; i < N; i++) { 64 | 65 | // Spaces before stars 66 | for (int j = 0; j < N - i - 1; j++) { 67 | cout << " "; 68 | } 69 | 70 | // Stars 71 | for (int j = 0; j < 2 * i + 1; j++) { 72 | cout << "*"; 73 | } 74 | 75 | // Spaces after stars 76 | for (int j = 0; j < N - i - 1; j++) { 77 | cout << " "; 78 | } 79 | 80 | // Move to next line 81 | cout << endl; 82 | } 83 | } 84 | 85 | int main() { 86 | int N = 5; // Example input 87 | pattern7(N); 88 | return 0; 89 | } 90 | ``` 91 | 92 | --- 93 | 94 | ## 🖥️ Output (When N = 5) 95 | 96 | ``` 97 | * 98 | *** 99 | ***** 100 | ******* 101 | ********* 102 | ``` 103 | 104 | --- 105 | 106 | ## 🖼️ Pattern Illustration 107 | 108 | > Save an image named `pattern7.png` inside the `images/` folder in your repository. 109 | 110 | ```markdown 111 | ![Pattern 7 – Star Pyramid](images/pattern7.png) 112 | ``` 113 | 114 | --- 115 | 116 | ## 📌 Notes 117 | 118 | - This pattern is useful to practice **nested loops** and **space management**. 119 | - The pyramid is **center-aligned**, requiring careful placement of spaces before and after stars. 120 | 121 | --- 122 | 123 | ## 🙌 Credits 124 | 125 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 126 | 127 | --- 128 | 129 | ## 🔗 Related Links 130 | 131 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 132 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 133 | 134 | --- 135 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/STL_C++/04_set.md: -------------------------------------------------------------------------------- 1 | # Set in C++ STL 2 | 3 | ## What is a Set? 4 | 5 | A **set** in C++ STL is a container that stores **unique elements** in a **particular order**. Duplicate values are not allowed. The underlying implementation is usually a balanced binary search tree (like Red-Black Tree). 6 | 7 | * **Average Case Time Complexity**: O(log n) for most operations (insertion, deletion, search) 8 | * **Worst Case Time Complexity**: O(n) 9 | 10 | --- 11 | 12 | ## Syntax 13 | 14 | ```cpp 15 | set variable_name; 16 | ``` 17 | 18 | ### Example 19 | 20 | ```cpp 21 | set s; 22 | set str; 23 | ``` 24 | 25 | --- 26 | 27 | ## Commonly Used Functions in Set 28 | 29 | * `insert(x)` – Inserts an element `x` into the set. 30 | * `begin()` – Returns an iterator pointing to the first element. 31 | * `end()` – Returns an iterator to the position after the last element. 32 | * `count(x)` – Returns `1` if element is present, otherwise `0`. 33 | * `clear()` – Deletes all elements from the set. 34 | * `find(x)` – Returns an iterator to element `x` if found, else `end()`. 35 | * `erase(x)` – Deletes a specific element or a range. 36 | * `size()` – Returns the size of the set. 37 | * `empty()` – Checks if the set is empty. 38 | 39 | --- 40 | 41 | ## Example Code 42 | 43 | ```cpp 44 | #include 45 | using namespace std; 46 | 47 | int main() { 48 | set s; 49 | for (int i = 1; i <= 10; i++) { 50 | s.insert(i); 51 | } 52 | 53 | cout << "Elements present in the set: "; 54 | for (auto it = s.begin(); it != s.end(); it++) { 55 | cout << *it << " "; 56 | } 57 | cout << endl; 58 | 59 | int n = 2; 60 | if (s.find(n) != s.end()) 61 | cout << n << " is present in set" << endl; 62 | 63 | s.erase(s.begin()); 64 | cout << "Elements after deleting the first element: "; 65 | for (auto it = s.begin(); it != s.end(); it++) { 66 | cout << *it << " "; 67 | } 68 | cout << endl; 69 | 70 | cout << "The size of the set is: " << s.size() << endl; 71 | 72 | if (!s.empty()) 73 | cout << "The set is not empty" << endl; 74 | else 75 | cout << "The set is empty" << endl; 76 | 77 | s.clear(); 78 | cout << "Size of the set after clearing all the elements: " << s.size(); 79 | } 80 | ``` 81 | 82 | --- 83 | 84 | ## Output 85 | 86 | ``` 87 | Elements present in the set: 1 2 3 4 5 6 7 8 9 10 88 | 2 is present in set 89 | Elements after deleting the first element: 2 3 4 5 6 7 8 9 10 90 | The size of the set is: 9 91 | The set is not empty 92 | Size of the set after clearing all the elements: 0 93 | ``` 94 | 95 | --- 96 | 97 | ## Other Useful Functions 98 | 99 | * `cbegin()` – Refers to the first element. 100 | * `cend()` – Refers to the theoretical element after the last element. 101 | * `rbegin()` – Points to the last element of the set. 102 | * `rend()` – Points before the first element. 103 | * `emplace(x)` – Inserts element `x` (faster than insert). 104 | * `max_size()` – Returns the maximum elements the set can hold. 105 | 106 | --- 107 | 108 | ✅ Sets are widely used when you need **unique sorted elements** with efficient insertion and search. 109 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/12_number_crown.md: -------------------------------------------------------------------------------- 1 | # 👑 Pattern-12: Number Crown Pattern 2 | 3 | --- 4 | 5 | ## 📝 Problem Statement 6 | 7 | Given an integer `N`, print a **Number Crown Pattern** consisting of increasing numbers on the left, spaces in the middle, and decreasing numbers on the right. 8 | 9 | --- 10 | 11 | ## ✅ Examples 12 | 13 | ### Example 1: 14 | **Input:** `N = 3` 15 | **Output:** 16 | ``` 17 | 1 1 18 | 12 21 19 | 123321 20 | ``` 21 | 22 | ### Example 2: 23 | **Input:** `N = 6` 24 | **Output:** 25 | ``` 26 | 1 1 27 | 12 21 28 | 123 321 29 | 1234 4321 30 | 12345 54321 31 | 123456654321 32 | ``` 33 | 34 | --- 35 | 36 | ## 🔍 Approach 37 | 38 | Follow the **4 golden rules** for pattern problems: 39 | 40 | 1. **Outer loop** → Runs from `1` to `N` (for each row). 41 | 2. **First inner loop** → Prints numbers from `1` to the current row index `i`. 42 | 3. **Second inner loop** → Prints spaces. 43 | - Initially, spaces = `2 * (N - 1)` for the first row. 44 | - Spaces decrease by `2` after each row. 45 | 4. **Third inner loop** → Prints numbers in reverse from `i` down to `1`. 46 | 47 | --- 48 | 49 | ### 🧠 Key Observations: 50 | - The pattern is **symmetric** with numbers mirrored on both sides. 51 | - Space count formula: `spaces = 2 * (N - i)`. 52 | 53 | --- 54 | 55 | ## ✅ Code (C++) 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void pattern12(int N) { 62 | int spaces = 2 * (N - 1); // Initial spaces 63 | for (int i = 1; i <= N; i++) { 64 | 65 | // Left side numbers (ascending) 66 | for (int j = 1; j <= i; j++) { 67 | cout << j; 68 | } 69 | 70 | // Middle spaces 71 | for (int j = 1; j <= spaces; j++) { 72 | cout << " "; 73 | } 74 | 75 | // Right side numbers (descending) 76 | for (int j = i; j >= 1; j--) { 77 | cout << j; 78 | } 79 | 80 | cout << endl; // Move to next row 81 | spaces -= 2; // Reduce space count 82 | } 83 | } 84 | 85 | int main() { 86 | int N = 5; // Example input 87 | pattern12(N); 88 | return 0; 89 | } 90 | ``` 91 | 92 | --- 93 | 94 | ## 🖥️ Output (When N = 5) 95 | 96 | ``` 97 | 1 1 98 | 12 21 99 | 123 321 100 | 1234 4321 101 | 1234554321 102 | ``` 103 | 104 | --- 105 | 106 | ## 🖼️ Pattern Illustration 107 | 108 | ```markdown 109 | ![Pattern 12 – Number Crown Pattern](images/pattern12.png) 110 | ``` 111 | 112 | --- 113 | 114 | ## 📌 Notes 115 | 116 | - Middle spaces decrease by `2` with each row. 117 | - Combines an **ascending number sequence** with a **mirrored descending sequence**. 118 | - Commonly used for symmetry-based problems in pattern printing. 119 | 120 | --- 121 | 122 | ## 🙌 Credits 123 | 124 | Special thanks to **Priyanshi Goel** for contributing this article to **TakeUForward**. 125 | 126 | --- 127 | 128 | ## 🔗 Related Links 129 | 130 | - [Striver’s A2Z DSA Sheet](https://takeuforward.org/interviews/strivers-a2z-dsa-course-sheet-2/) 131 | - [Pattern Problems Playlist](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 132 | 133 | --- 134 | -------------------------------------------------------------------------------- /03_Arrays/01_Easy_problems/07_move_zeros_to_end.md: -------------------------------------------------------------------------------- 1 | # ✅ Move All Zeros to the End of the Array 2 | 3 | **Problem Statement:** You are given an array of integers, your task is to move all the zeros in the array to the end of the array while maintaining the order of non-zero elements. 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Given an array of size `N`, move all zeros to the end while keeping the order of non-zero elements. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | ``` 17 | Input: array[] = {1, 0, 2, 0, 3, 4} 18 | Output: {1, 2, 3, 4, 0, 0} 19 | ``` 20 | 21 | ### Example 2: 22 | ``` 23 | Input: array[] = {0, 1, 0, 3, 12} 24 | Output: {1, 3, 12, 0, 0} 25 | ``` 26 | 27 | --- 28 | 29 | ## 💡 Approaches 30 | 31 | ### Approach 1: Using a Temp Array 32 | 33 | **Algorithm:** 34 | 1. Create a temporary array to store non-zero elements. 35 | 2. Copy non-zero elements from the original array to the temporary array. 36 | 3. Fill the remaining positions in the original array with zeros. 37 | 38 | #### Code (C++) 39 | ```cpp 40 | #include 41 | using namespace std; 42 | 43 | vector moveZeros(int n, vector a) { 44 | vector temp; 45 | for (int i = 0; i < n; i++) { 46 | if (a[i] != 0) 47 | temp.push_back(a[i]); 48 | } 49 | 50 | int nz = temp.size(); 51 | for (int i = 0; i < nz; i++) { 52 | a[i] = temp[i]; 53 | } 54 | for (int i = nz; i < n; i++) { 55 | a[i] = 0; 56 | } 57 | return a; 58 | } 59 | 60 | int main() { 61 | vector arr = {1, 0, 2, 0, 3, 4}; 62 | int n = 6; 63 | vector ans = moveZeros(n, arr); 64 | for (auto &it : ans) { 65 | cout << it << " "; 66 | } 67 | cout << '\n'; 68 | return 0; 69 | } 70 | ``` 71 | **Output:** 1 2 3 4 0 0 72 | 73 | **Time Complexity:** O(N) 74 | 75 | **Space Complexity:** O(N) for the temporary array. 76 | 77 | ### Approach 2: Using Two Pointers 78 | 79 | **Algorithm:** 80 | 1. Use two pointers, one for traversing the array and another for tracking the position of the last non-zero element. 81 | 2. Swap elements as necessary to move zeros to the end. 82 | 83 | #### Code (C++) 84 | ```cpp 85 | #include 86 | using namespace std; 87 | 88 | vector moveZeros(int n, vector a) { 89 | int j = -1; 90 | for (int i = 0; i < n; i++) { 91 | if (a[i] == 0) { 92 | j = i; 93 | break; 94 | } 95 | } 96 | 97 | if (j == -1) return a; 98 | 99 | for (int i = j + 1; i < n; i++) { 100 | if (a[i] != 0) { 101 | swap(a[i], a[j]); 102 | j++; 103 | } 104 | } 105 | return a; 106 | } 107 | 108 | int main() { 109 | vector arr = {1, 0, 2, 0, 3, 4}; 110 | int n = 6; 111 | vector ans = moveZeros(n, arr); 112 | for (auto &it : ans) { 113 | cout << it << " "; 114 | } 115 | cout << '\n'; 116 | return 0; 117 | } 118 | ``` 119 | **Output:** 1 2 3 4 0 0 120 | 121 | **Time Complexity:** O(N) 122 | 123 | **Space Complexity:** O(1) since no extra space is used. 124 | 125 | --- 126 | 127 | ## 🙌 Credits 128 | 129 | Special thanks to Sai Bargav Nellepalli and Kritidipta Ghosh for contributing to this article on TakeUforward. 130 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Basic_Math/04_gcd_of_two_numbers.md: -------------------------------------------------------------------------------- 1 | # ✅ GCD of Two Numbers 2 | 3 | **Problem Statement:** Given two integers A and B, find their greatest common divisor (GCD). 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Write a function to compute the GCD of two given integers A and B. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | **Input:** 17 | `A = 48, B = 18` 18 | **Output:** 19 | `6` 20 | 21 | ### Example 2: 22 | **Input:** 23 | `A = 56, B = 98` 24 | **Output:** 25 | `14` 26 | 27 | --- 28 | 29 | ## 💡 Approach 30 | 31 | ### 1) Euclidean Algorithm 32 | 33 | **Intuition:** The GCD of two numbers can be found using the formula: 34 | - GCD(A, B) = GCD(B, A % B) 35 | 36 | #### Pseudocode 37 | ``` 38 | while B != 0: 39 | A, B = B, A % B 40 | return A 41 | ``` 42 | 43 | #### Code (C++) 44 | ```cpp 45 | #include 46 | using namespace std; 47 | 48 | int gcd(int a, int b) { 49 | while (b != 0) { 50 | int temp = b; 51 | b = a % b; 52 | a = temp; 53 | } 54 | return a; 55 | } 56 | 57 | int main() { 58 | int a = 48, b = 18; 59 | cout << "GCD: " << gcd(a, b) << endl; 60 | return 0; 61 | } 62 | ``` 63 | 64 | **Output:** 65 | ``` 66 | GCD: 6 67 | ``` 68 | 69 | **Complexity Analysis:** 70 | - Time Complexity: `O(log(min(A, B)))` 71 | - Space Complexity: `O(1)` (no extra space used) 72 | 73 | --- 74 | 75 | ## 🧷 Implementations 76 | 77 | ### Java 78 | 79 |
80 | GCD of Two Numbers 81 | 82 | ```java 83 | public class Main { 84 | static int gcd(int a, int b) { 85 | while (b != 0) { 86 | int temp = b; 87 | b = a % b; 88 | a = temp; 89 | } 90 | return a; 91 | } 92 | 93 | public static void main(String[] args) { 94 | int a = 48, b = 18; 95 | System.out.println("GCD: " + gcd(a, b)); 96 | } 97 | } 98 | ``` 99 | 100 |
101 | 102 | ### Python 103 | 104 |
105 | GCD of Two Numbers 106 | 107 | ```python 108 | def gcd(a, b): 109 | while b != 0: 110 | a, b = b, a % b 111 | return a 112 | 113 | a = 48 114 | b = 18 115 | print("GCD:", gcd(a, b)) 116 | ``` 117 | 118 |
119 | 120 | ### JavaScript 121 | 122 |
123 | GCD of Two Numbers 124 | 125 | ```javascript 126 | function gcd(a, b) { 127 | while (b !== 0) { 128 | let temp = b; 129 | b = a % b; 130 | a = temp; 131 | } 132 | return a; 133 | } 134 | 135 | let a = 48; 136 | let b = 18; 137 | console.log("GCD:", gcd(a, b)); 138 | ``` 139 | 140 |
141 | 142 | --- 143 | 144 | ## 🧭 Edge Cases to Consider 145 | 146 | * If either number is 0, the GCD is the other number. 147 | * Negative numbers (GCD is always positive). 148 | 149 | --- 150 | 151 | ## 🧾 Complexity Summary 152 | 153 | | Approach | Time Complexity | Space Complexity | 154 | | ------------- | --------------- | ---------------- | 155 | | Euclidean | `O(log(min(A, B)))` | `O(1)` | 156 | 157 | --- 158 | 159 | ## 🙌 Credits 160 | 161 | Special thanks to **Ayush Pandey** for contributing to this article on TakeUforward. 162 | 163 | --- 164 | 165 | ## 📣 Notes 166 | 167 | * This problem is a common exercise for beginners to understand number theory. 168 | * Variations can include finding the LCM (Least Common Multiple) using GCD. 169 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Recursion/Extra_Problems/04_sum_of_n_numbers.md: -------------------------------------------------------------------------------- 1 | # ✅ Sum of N Numbers Using Recursion 2 | 3 | **Problem Statement:** Calculate the sum of the first N natural numbers using recursion. 4 | 5 | --- 6 | 7 | ## 📌 What is the Sum of N Natural Numbers? 8 | 9 | The sum of the first N natural numbers is the total obtained by adding all natural numbers from 1 to N. 10 | 11 | ### Formula: 12 | - Sum(N) = 1 + 2 + 3 + ... + N 13 | 14 | --- 15 | 16 | ## 🧪 Examples 17 | 18 | ### Example 1: 19 | **Input:** 20 | `N = 5` 21 | **Output:** 22 | `15` (1 + 2 + 3 + 4 + 5) 23 | 24 | ### Example 2: 25 | **Input:** 26 | `N = 10` 27 | **Output:** 28 | `55` (1 + 2 + 3 + ... + 10) 29 | 30 | --- 31 | 32 | ## 💡 Approach 33 | 34 | ### Recursive Approach 35 | 36 | **Intuition:** The sum can be defined in terms of the sum of (N - 1): 37 | - Sum(N) = N + Sum(N - 1) 38 | 39 | #### Pseudocode 40 | ``` 41 | function sum(n): 42 | if n == 0: 43 | return 0 44 | return n + sum(n - 1) 45 | ``` 46 | 47 | #### Code (C++) 48 | ```cpp 49 | #include 50 | using namespace std; 51 | 52 | int sum(int n) { 53 | if (n == 0) return 0; // Base case 54 | return n + sum(n - 1); // Recursive call 55 | } 56 | 57 | int main() { 58 | int n = 5; 59 | cout << "Sum: " << sum(n) << endl; 60 | return 0; 61 | } 62 | ``` 63 | 64 | **Output:** 65 | ``` 66 | Sum: 15 67 | ``` 68 | 69 | **Complexity Analysis:** 70 | - Time Complexity: `O(N)` where N is the input number. 71 | - Space Complexity: `O(N)` due to the call stack. 72 | 73 | --- 74 | 75 | ## 🧷 Implementations 76 | 77 | ### Java 78 | 79 |
80 | Sum of N Numbers Using Recursion 81 | 82 | ```java 83 | public class Main { 84 | static int sum(int n) { 85 | if (n == 0) return 0; // Base case 86 | return n + sum(n - 1); // Recursive call 87 | } 88 | 89 | public static void main(String[] args) { 90 | int n = 5; 91 | System.out.println("Sum: " + sum(n)); 92 | } 93 | } 94 | ``` 95 | 96 |
97 | 98 | ### Python 99 | 100 |
101 | Sum of N Numbers Using Recursion 102 | 103 | ```python 104 | def sum(n): 105 | if n == 0: 106 | return 0 # Base case 107 | return n + sum(n - 1) # Recursive call 108 | 109 | n = 5 110 | print("Sum:", sum(n)) 111 | ``` 112 | 113 |
114 | 115 | ### JavaScript 116 | 117 |
118 | Sum of N Numbers Using Recursion 119 | 120 | ```javascript 121 | function sum(n) { 122 | if (n === 0) return 0; // Base case 123 | return n + sum(n - 1); // Recursive call 124 | } 125 | 126 | let n = 5; 127 | console.log("Sum:", sum(n)); 128 | ``` 129 | 130 |
131 | 132 | --- 133 | 134 | ## 🧭 Edge Cases to Consider 135 | 136 | * `N = 0` (should return 0) 137 | * Negative numbers (should handle gracefully) 138 | 139 | --- 140 | 141 | ## 🧾 Complexity Summary 142 | 143 | | Approach | Time Complexity | Space Complexity | 144 | | ------------- | --------------- | ---------------- | 145 | | Recursive | `O(N)` | `O(N)` | 146 | 147 | --- 148 | 149 | ## 🙌 Credits 150 | 151 | Special thanks to **Striver** for the comprehensive A2Z DSA Course on TakeUforward. 152 | 153 | --- 154 | 155 | ## 📣 Notes 156 | 157 | * Recursion is a powerful tool but can lead to stack overflow if not handled properly. 158 | * Understanding recursion is crucial for solving complex problems like tree traversals and dynamic programming. 159 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Basic_Math/06_print_all_divisors.md: -------------------------------------------------------------------------------- 1 | # ✅ Print All Divisors of a Number 2 | 3 | **Problem Statement:** Given an integer N, print all divisors of the number. 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Write a function to print all divisors of a given integer N. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | **Input:** 17 | `N = 12` 18 | **Output:** 19 | `1 2 3 4 6 12` 20 | 21 | ### Example 2: 22 | **Input:** 23 | `N = 15` 24 | **Output:** 25 | `1 3 5 15` 26 | 27 | ### Example 3: 28 | **Input:** 29 | `N = 7` 30 | **Output:** 31 | `1 7` 32 | 33 | --- 34 | 35 | ## 💡 Approach 36 | 37 | ### 1) Iterative Approach 38 | 39 | **Intuition:** Iterate from 1 to N and check if the number is a divisor. 40 | 41 | #### Pseudocode 42 | ``` 43 | for i from 1 to N: 44 | if N % i == 0: 45 | print(i) 46 | ``` 47 | 48 | #### Code (C++) 49 | ```cpp 50 | #include 51 | using namespace std; 52 | 53 | void printDivisors(int n) { 54 | for (int i = 1; i <= n; i++) { 55 | if (n % i == 0) { 56 | cout << i << " "; 57 | } 58 | } 59 | cout << endl; 60 | } 61 | 62 | int main() { 63 | int n = 12; 64 | printDivisors(n); 65 | return 0; 66 | } 67 | ``` 68 | 69 | **Output:** 70 | ``` 71 | 1 2 3 4 6 12 72 | ``` 73 | 74 | **Complexity Analysis:** 75 | - Time Complexity: `O(N)` 76 | - Space Complexity: `O(1)` (no extra space used) 77 | 78 | --- 79 | 80 | ## 🧷 Implementations 81 | 82 | ### Java 83 | 84 |
85 | Print All Divisors 86 | 87 | ```java 88 | public class Main { 89 | static void printDivisors(int n) { 90 | for (int i = 1; i <= n; i++) { 91 | if (n % i == 0) { 92 | System.out.print(i + " "); 93 | } 94 | } 95 | System.out.println(); 96 | } 97 | 98 | public static void main(String[] args) { 99 | int n = 12; 100 | printDivisors(n); 101 | } 102 | } 103 | ``` 104 | 105 |
106 | 107 | ### Python 108 | 109 |
110 | Print All Divisors 111 | 112 | ```python 113 | def print_divisors(n): 114 | for i in range(1, n + 1): 115 | if n % i == 0: 116 | print(i, end=" ") 117 | print() 118 | 119 | n = 12 120 | print_divisors(n) 121 | ``` 122 | 123 |
124 | 125 | ### JavaScript 126 | 127 |
128 | Print All Divisors 129 | 130 | ```javascript 131 | function printDivisors(n) { 132 | let divisors = ""; 133 | for (let i = 1; i <= n; i++) { 134 | if (n % i === 0) { 135 | divisors += i + " "; 136 | } 137 | } 138 | console.log(divisors); 139 | } 140 | 141 | let n = 12; 142 | printDivisors(n); 143 | ``` 144 | 145 |
146 | 147 | --- 148 | 149 | ## 🧭 Edge Cases to Consider 150 | 151 | * `N = 0` (should handle gracefully) 152 | * Negative numbers (should consider absolute value) 153 | 154 | --- 155 | 156 | ## 🧾 Complexity Summary 157 | 158 | | Approach | Time Complexity | Space Complexity | 159 | | ------------- | --------------- | ---------------- | 160 | | Iterative | `O(N)` | `O(1)` | 161 | 162 | --- 163 | 164 | ## 🙌 Credits 165 | 166 | Special thanks to **Ayush Pandey** for contributing to this article on TakeUforward. 167 | 168 | --- 169 | 170 | ## 📣 Notes 171 | 172 | * This problem is a common exercise for beginners to understand number theory. 173 | * Variations can include finding the sum of divisors or the number of divisors. 174 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Basic_C++/08_function.md: -------------------------------------------------------------------------------- 1 | # ⚙️ 10. Functions in C++ – Pass by Value & Reference | Striver’s A2Z DSA Course 2 | 3 | --- 4 | 5 | ## ✅ What Are Functions? 6 | 7 | A **function** is a block of code that performs a specific task. 8 | It improves code **reusability**, **modularity**, and **readability**. 9 | 10 | ```cpp 11 | // Syntax: 12 | returnType functionName(parameters) { 13 | // code 14 | return value; 15 | } 16 | ``` 17 | 18 | --- 19 | 20 | ## 📌 Function Categories 21 | 22 | | Type | Description | 23 | |---------------|----------------------------------------| 24 | | 🟢 User-defined | Created by the programmer | 25 | | 🟢 Library | Provided by C++ standard library (e.g. pow(), sqrt()) | 26 | 27 | --- 28 | 29 | ## 1️⃣ Pass by Value 30 | 31 | A copy of the argument is passed to the function. 32 | 🔸 Changes don’t affect the original variable. 33 | 34 | ```cpp 35 | #include 36 | using namespace std; 37 | 38 | void update(int x) { 39 | x = x + 10; 40 | cout << "[Inside] x = " << x << endl; 41 | } 42 | 43 | int main() { 44 | int a = 5; 45 | update(a); 46 | cout << "[Outside] a = " << a << endl; 47 | return 0; 48 | } 49 | ``` 50 | 51 | 🖥️ Output: 52 | ``` 53 | [Inside] x = 15 54 | [Outside] a = 5 55 | ``` 56 | 57 | 📌 No change to the original variable. 58 | 59 | --- 60 | 61 | ## 2️⃣ Pass by Reference 62 | 63 | The actual memory address is passed. 64 | 🔸 Changes **do** affect the original variable. 65 | 66 | ```cpp 67 | #include 68 | using namespace std; 69 | 70 | void update(int &x) { 71 | x = x + 10; 72 | cout << "[Inside] x = " << x << endl; 73 | } 74 | 75 | int main() { 76 | int a = 5; 77 | update(a); 78 | cout << "[Outside] a = " << a << endl; 79 | return 0; 80 | } 81 | ``` 82 | 83 | 🖥️ Output: 84 | ``` 85 | [Inside] x = 15 86 | [Outside] a = 15 87 | ``` 88 | 89 | 📌 Reference (`&`) modifies the original variable. 90 | 91 | --- 92 | 93 | ## 🧪 Example: Swap Two Numbers 94 | 95 | ### ✅ Using Pass by Value (Fails) 96 | 97 | ```cpp 98 | #include 99 | using namespace std; 100 | 101 | void swap(int a, int b) { 102 | int temp = a; 103 | a = b; 104 | b = temp; 105 | } 106 | 107 | int main() { 108 | int x = 10, y = 20; 109 | swap(x, y); 110 | cout << "x = " << x << ", y = " << y << endl; 111 | return 0; 112 | } 113 | ``` 114 | 115 | 🖥️ Output: 116 | ``` 117 | x = 10, y = 20 118 | ``` 119 | 120 | 🚫 No actual swap happens in `main()`. 121 | 122 | --- 123 | 124 | ### ✅ Using Pass by Reference (Works) 125 | 126 | ```cpp 127 | #include 128 | using namespace std; 129 | 130 | void swap(int &a, int &b) { 131 | int temp = a; 132 | a = b; 133 | b = temp; 134 | } 135 | 136 | int main() { 137 | int x = 10, y = 20; 138 | swap(x, y); 139 | cout << "x = " << x << ", y = " << y << endl; 140 | return 0; 141 | } 142 | ``` 143 | 144 | 🖥️ Output: 145 | ``` 146 | x = 20, y = 10 147 | ``` 148 | 149 | ✅ Swaps values directly in `main()`. 150 | 151 | --- 152 | 153 | ## 🧠 Summary Table 154 | 155 | | Method | Description | Can Modify Original? | 156 | |--------------------|----------------------------------|-----------------------| 157 | | Pass by Value | Passes a copy of the value | ❌ No | 158 | | Pass by Reference | Passes a reference (address) | ✅ Yes | 159 | 160 | --- 161 | 162 | 🙌 Special thanks to **Gauri Tomar** for contributing this content to TakeUForward. 163 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Recursion/01_introduction_to_recursion.md: -------------------------------------------------------------------------------- 1 | # ✅ Introduction to Recursion 2 | 3 | **Topic:** Understanding Recursion by Printing Something N Times 4 | 5 | --- 6 | 7 | ## 📌 What is Recursion? 8 | 9 | Recursion is a programming technique where a function calls itself to solve a problem. It is often used to solve problems that can be broken down into smaller, similar subproblems. 10 | 11 | --- 12 | 13 | ## 🎯 Key Concepts 14 | 15 | ### 1. Base Case 16 | The condition under which the recursion stops. It prevents infinite recursion. 17 | 18 | ### 2. Recursive Case 19 | The part of the function where the function calls itself with a modified argument. 20 | 21 | --- 22 | 23 | ## 🧪 Example: Print "Hello" N Times 24 | 25 | ### Problem Statement 26 | Write a recursive function to print "Hello" N times. 27 | 28 | ### Pseudocode 29 | ``` 30 | function printHello(n): 31 | if n <= 0: 32 | return 33 | print("Hello") 34 | printHello(n - 1) 35 | ``` 36 | 37 | ### Code (C++) 38 | ```cpp 39 | #include 40 | using namespace std; 41 | 42 | void printHello(int n) { 43 | if (n <= 0) return; // Base case 44 | cout << "Hello" << endl; // Print 45 | printHello(n - 1); // Recursive call 46 | } 47 | 48 | int main() { 49 | int n = 5; 50 | printHello(n); 51 | return 0; 52 | } 53 | ``` 54 | 55 | **Output:** 56 | ``` 57 | Hello 58 | Hello 59 | Hello 60 | Hello 61 | Hello 62 | ``` 63 | 64 | **Complexity Analysis:** 65 | - Time Complexity: `O(N)` where N is the number of times to print. 66 | - Space Complexity: `O(N)` due to the call stack. 67 | 68 | --- 69 | 70 | ## 🧷 Implementations 71 | 72 | ### Java 73 | 74 |
75 | Print Hello N Times 76 | 77 | ```java 78 | public class Main { 79 | static void printHello(int n) { 80 | if (n <= 0) return; // Base case 81 | System.out.println("Hello"); // Print 82 | printHello(n - 1); // Recursive call 83 | } 84 | 85 | public static void main(String[] args) { 86 | int n = 5; 87 | printHello(n); 88 | } 89 | } 90 | ``` 91 | 92 |
93 | 94 | ### Python 95 | 96 |
97 | Print Hello N Times 98 | 99 | ```python 100 | def print_hello(n): 101 | if n <= 0: 102 | return # Base case 103 | print("Hello") # Print 104 | print_hello(n - 1) # Recursive call 105 | 106 | n = 5 107 | print_hello(n) 108 | ``` 109 | 110 |
111 | 112 | ### JavaScript 113 | 114 |
115 | Print Hello N Times 116 | 117 | ```javascript 118 | function printHello(n) { 119 | if (n <= 0) return; // Base case 120 | console.log("Hello"); // Print 121 | printHello(n - 1); // Recursive call 122 | } 123 | 124 | let n = 5; 125 | printHello(n); 126 | ``` 127 | 128 |
129 | 130 | --- 131 | 132 | ## 🧭 Edge Cases to Consider 133 | 134 | * `N = 0` (should not print anything) 135 | * Negative values of N (should not print anything) 136 | 137 | --- 138 | 139 | ## 🧾 Complexity Summary 140 | 141 | | Approach | Time Complexity | Space Complexity | 142 | | ------------- | --------------- | ---------------- | 143 | | Recursive | `O(N)` | `O(N)` | 144 | 145 | --- 146 | 147 | ## 🙌 Credits 148 | 149 | Special thanks to **Striver** for the comprehensive A2Z DSA Course on TakeUforward. 150 | 151 | --- 152 | 153 | ## 📣 Notes 154 | 155 | * Recursion is a powerful tool but can lead to stack overflow if not handled properly. 156 | * Understanding recursion is crucial for solving complex problems like tree traversals and dynamic programming. 157 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Basic_C++/06_for_loop.md: -------------------------------------------------------------------------------- 1 | # 🔁 07. Understanding For Loop 2 | --- 3 | 4 | ## 🚀 What is a For Loop? 5 | 6 | A **for loop** is a control structure that allows repeated execution of a block of code. It’s ideal for situations where the number of iterations is **known in advance**. 7 | 8 | ### 🔹 Components of a For Loop: 9 | 10 | 1. **Initialization** – set up a counter (e.g. `int i = 0`) 11 | 2. **Condition** – loop continues as long as this is true (`i <= 10`) 12 | 3. **Increment/Decrement** – update counter (`i++`) 13 | 14 | --- 15 | 16 | ## 💻 Example: Basic For Loop 17 | 18 | ```cpp 19 | #include 20 | using namespace std; 21 | 22 | int main() { 23 | for (int i = 1; i <= 10; i++) { 24 | cout << "Hey, Striver, this is the " << i << "'th iteration" << endl; 25 | } 26 | return 0; 27 | } 28 | ``` 29 | 30 | ### ✅ Output: 31 | 32 | ``` 33 | Hey, Striver, this is the 1'th iteration 34 | Hey, Striver, this is the 2'th iteration 35 | ... 36 | Hey, Striver, this is the 10'th iteration 37 | ``` 38 | 39 | - Loop starts from `i = 1` 40 | - Ends when `i > 10` 41 | - `i++` increases `i` by 1 each time 42 | 43 | --- 44 | 45 | ## 🔄 For Loop Execution Flow 46 | 47 | 1. **Start** → Enters loop 48 | 2. **Initialize** → Set counter `i = 0` 49 | 3. **Condition Check** → Is `i < N`? 50 | 4. ✅ **True** → Run loop body → Increment `i` 51 | 5. 🔁 Go back to condition 52 | 6. ❌ **False** → Exit loop → Run code after loop 53 | 54 | --- 55 | 56 | ## 🔁 Nested For Loops 57 | 58 | Used when you need to loop inside another loop (e.g. 2D arrays, patterns). 59 | 60 | ```cpp 61 | #include 62 | using namespace std; 63 | 64 | int main() { 65 | for (int i = 0; i < 3; i++) { 66 | for (int j = 0; j < 3; j++) { 67 | cout << "i = " << i << ", j = " << j << endl; 68 | } 69 | } 70 | return 0; 71 | } 72 | ``` 73 | 74 | ### ✅ Output: 75 | 76 | ``` 77 | i = 0, j = 0 78 | i = 0, j = 1 79 | i = 0, j = 2 80 | i = 1, j = 0 81 | ... 82 | i = 2, j = 2 83 | ``` 84 | 85 | --- 86 | 87 | ## ⚡ Conditional Statements in For Loops 88 | 89 | You can include `if`, `else if`, or `else` inside a loop to handle custom logic. 90 | 91 | ```cpp 92 | for (int i = 1; i <= 10; i++) { 93 | if (i % 2 == 0) { 94 | // Even number logic 95 | } else { 96 | // Odd number logic 97 | } 98 | } 99 | ``` 100 | 101 | --- 102 | 103 | ## 🛠 Customizing For Loop 104 | 105 | You can change step sizes, start points, and end conditions. 106 | 107 | ```cpp 108 | #include 109 | using namespace std; 110 | 111 | int main() { 112 | for (int i = 1; i <= 25; i += 5) { 113 | cout << "i = " << i << endl; 114 | } 115 | return 0; 116 | } 117 | ``` 118 | 119 | ### ✅ Output: 120 | 121 | ``` 122 | i = 1 123 | i = 6 124 | i = 11 125 | i = 16 126 | i = 21 127 | ``` 128 | 129 | - Starts at 1 130 | - Increments by 5 131 | - Ends when `i > 25` 132 | 133 | --- 134 | 135 | ## 🧠 Summary 136 | 137 | | Feature | Description | 138 | |----------------------|------------------------------------------------| 139 | | `Initialization` | Sets up loop control variable | 140 | | `Condition` | Loop continues while true | 141 | | `Increment/Decrement` | Updates variable each iteration | 142 | | `Nested Loops` | Loop inside loop for 2D structures | 143 | | `Conditionals Inside` | Add decision-making with `if-else` logic | 144 | | `Custom Steps` | Use `i += X`, `i -= X`, or different ranges | 145 | 146 | --- 147 | 148 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Recursion/Extra_Problems/03_power_using_recursion.md: -------------------------------------------------------------------------------- 1 | # ✅ Power Using Recursion 2 | 3 | **Problem Statement:** Calculate the power of a number N raised to the exponent P using recursion. 4 | 5 | --- 6 | 7 | ## 📌 What is Power? 8 | 9 | The power of a number is the result of multiplying that number by itself a certain number of times. It is denoted as \( N^P \). 10 | 11 | ### Formula: 12 | - \( N^P = N \times N \times ... \) (P times) 13 | 14 | --- 15 | 16 | ## 🧪 Examples 17 | 18 | ### Example 1: 19 | **Input:** 20 | `N = 2, P = 3` 21 | **Output:** 22 | `8` (2^3 = 2 × 2 × 2) 23 | 24 | ### Example 2: 25 | **Input:** 26 | `N = 5, P = 0` 27 | **Output:** 28 | `1` (5^0 = 1) 29 | 30 | --- 31 | 32 | ## 💡 Approach 33 | 34 | ### Recursive Approach 35 | 36 | **Intuition:** The power can be defined in terms of the power of (P - 1): 37 | - \( N^P = N \times N^{(P - 1)} \) 38 | 39 | #### Pseudocode 40 | ``` 41 | function power(N, P): 42 | if P == 0: 43 | return 1 44 | return N * power(N, P - 1) 45 | ``` 46 | 47 | #### Code (C++) 48 | ```cpp 49 | #include 50 | using namespace std; 51 | 52 | int power(int N, int P) { 53 | if (P == 0) return 1; // Base case 54 | return N * power(N, P - 1); // Recursive call 55 | } 56 | 57 | int main() { 58 | int N = 2, P = 3; 59 | cout << "Power: " << power(N, P) << endl; 60 | return 0; 61 | } 62 | ``` 63 | 64 | **Output:** 65 | ``` 66 | Power: 8 67 | ``` 68 | 69 | **Complexity Analysis:** 70 | - Time Complexity: `O(P)` where P is the exponent. 71 | - Space Complexity: `O(P)` due to the call stack. 72 | 73 | --- 74 | 75 | ## 🧷 Implementations 76 | 77 | ### Java 78 | 79 |
80 | Power Using Recursion 81 | 82 | ```java 83 | public class Main { 84 | static int power(int N, int P) { 85 | if (P == 0) return 1; // Base case 86 | return N * power(N, P - 1); // Recursive call 87 | } 88 | 89 | public static void main(String[] args) { 90 | int N = 2, P = 3; 91 | System.out.println("Power: " + power(N, P)); 92 | } 93 | } 94 | ``` 95 | 96 |
97 | 98 | ### Python 99 | 100 |
101 | Power Using Recursion 102 | 103 | ```python 104 | def power(N, P): 105 | if P == 0: 106 | return 1 # Base case 107 | return N * power(N, P - 1) # Recursive call 108 | 109 | N = 2 110 | P = 3 111 | print("Power:", power(N, P)) 112 | ``` 113 | 114 |
115 | 116 | ### JavaScript 117 | 118 |
119 | Power Using Recursion 120 | 121 | ```javascript 122 | function power(N, P) { 123 | if (P === 0) return 1; // Base case 124 | return N * power(N, P - 1); // Recursive call 125 | } 126 | 127 | let N = 2; 128 | let P = 3; 129 | console.log("Power:", power(N, P)); 130 | ``` 131 | 132 |
133 | 134 | --- 135 | 136 | ## 🧭 Edge Cases to Consider 137 | 138 | * `P = 0` (should return 1) 139 | * Negative values of P (should handle gracefully) 140 | 141 | --- 142 | 143 | ## 🧾 Complexity Summary 144 | 145 | | Approach | Time Complexity | Space Complexity | 146 | | ------------- | --------------- | ---------------- | 147 | | Recursive | `O(P)` | `O(P)` | 148 | 149 | --- 150 | 151 | ## 🙌 Credits 152 | 153 | Special thanks to **Striver** for the comprehensive A2Z DSA Course on TakeUforward. 154 | 155 | --- 156 | 157 | ## 📣 Notes 158 | 159 | * Recursion is a powerful tool but can lead to stack overflow if not handled properly. 160 | * Understanding recursion is crucial for solving complex problems like tree traversals and dynamic programming. 161 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/STL_C++/02_unordered_set.md: -------------------------------------------------------------------------------- 1 | # 🔑 Unordered Set in C++ STL 2 | 3 | ## 📌 What is an Unordered Set? 4 | 5 | An **unordered\_set** in C++ STL is a container that stores **unique elements** in **no particular order**. 6 | 7 | * Average case time complexity: **O(1)** for insertion, deletion, and search 8 | * Worst case time complexity: **O(n)** 9 | 10 | --- 11 | 12 | ## ⚙️ Syntax 13 | 14 | ```cpp 15 | unordered_set variable_name; 16 | ``` 17 | 18 | ### Example 19 | 20 | ```cpp 21 | unordered_set s; 22 | unordered_set str; 23 | ``` 24 | 25 | --- 26 | 27 | ## 🛠️ Common Functions in `unordered_set` 28 | 29 | ### 🔹 Insert Elements 30 | 31 | ```cpp 32 | unordered_set s; 33 | s.insert(1); 34 | s.insert(2); 35 | ``` 36 | 37 | ### 🔹 Begin & End 38 | 39 | ```cpp 40 | s.begin(); // Iterator to first element 41 | s.end(); // Iterator to element after the last 42 | ``` 43 | 44 | ### 🔹 Count (check existence) 45 | 46 | ```cpp 47 | s.count(2); // returns 1 if present, else 0 48 | ``` 49 | 50 | ### 🔹 Clear 51 | 52 | ```cpp 53 | s.clear(); // Removes all elements 54 | ``` 55 | 56 | ### 🔹 Find 57 | 58 | ```cpp 59 | if(s.find(2) != s.end()) 60 | cout << "Found"; 61 | ``` 62 | 63 | ### 🔹 Erase 64 | 65 | ```cpp 66 | s.erase(2); // Remove specific element 67 | s.erase(s.begin()); // Remove first element 68 | ``` 69 | 70 | ### 🔹 Size & Empty 71 | 72 | ```cpp 73 | s.size(); // Number of elements 74 | s.empty(); // Check if set is empty 75 | ``` 76 | 77 | --- 78 | 79 | ## 📝 Example Code 80 | 81 | ```cpp 82 | #include 83 | using namespace std; 84 | 85 | int main() { 86 | unordered_set s; 87 | for (int i = 1; i <= 10; i++) { 88 | s.insert(i); 89 | } 90 | 91 | cout << "Elements present in the unordered set: "; 92 | for (auto it = s.begin(); it != s.end(); it++) { 93 | cout << *it << " "; 94 | } 95 | cout << endl; 96 | 97 | int n = 2; 98 | if (s.find(2) != s.end()) 99 | cout << n << " is present in unordered set" << endl; 100 | 101 | s.erase(s.begin()); 102 | cout << "Elements after deleting the first element: "; 103 | for (auto it = s.begin(); it != s.end(); it++) { 104 | cout << *it << " "; 105 | } 106 | cout << endl; 107 | 108 | cout << "The size of the unordered set is: " << s.size() << endl; 109 | 110 | if (!s.empty()) 111 | cout << "The unordered set is not empty" << endl; 112 | else 113 | cout << "The unordered set is empty" << endl; 114 | 115 | s.clear(); 116 | cout << "Size of the unordered set after clearing all the elements: " << s.size(); 117 | } 118 | ``` 119 | 120 | ### ✅ Output 121 | 122 | ``` 123 | Elements present in the unordered set: 10 9 8 7 2 1 3 4 5 6 124 | 2 is present in unordered set 125 | Elements after deleting the first element: 9 8 7 2 1 3 4 5 6 126 | The size of the unordered set is: 9 127 | The unordered set is not empty 128 | Size of the unordered set after clearing all the elements: 0 129 | ``` 130 | 131 | --- 132 | 133 | ## 📚 Other Useful Functions 134 | 135 | * **`cbegin()`** → Iterator to first element (const) 136 | * **`cend()`** → Iterator after last element (const) 137 | * **`bucket_size()`** → Number of elements in a specific bucket 138 | * **`emplace()`** → Insert element in place 139 | * **`max_size()`** → Maximum elements it can hold 140 | * **`max_bucket_count()`** → Maximum number of buckets available 141 | 142 | --- 143 | 144 | 🚀 The `unordered_set` is widely used for **fast lookups, uniqueness checks, and frequency counting** in C++ programming. 145 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Recursion/Extra_Problems/01_factorial_using_recursion.md: -------------------------------------------------------------------------------- 1 | # ✅ Factorial Using Recursion 2 | 3 | **Problem Statement:** Calculate the factorial of a given integer N using recursion. 4 | 5 | --- 6 | 7 | ## 📌 What is Factorial? 8 | 9 | The factorial of a non-negative integer N is the product of all positive integers less than or equal to N. It is denoted by N!. 10 | 11 | ### Formula: 12 | - N! = N × (N - 1) × (N - 2) × ... × 1 13 | - 0! = 1 (by definition) 14 | 15 | --- 16 | 17 | ## 🧪 Examples 18 | 19 | ### Example 1: 20 | **Input:** 21 | `N = 5` 22 | **Output:** 23 | `120` (5! = 5 × 4 × 3 × 2 × 1) 24 | 25 | ### Example 2: 26 | **Input:** 27 | `N = 0` 28 | **Output:** 29 | `1` (0! = 1) 30 | 31 | --- 32 | 33 | ## 💡 Approach 34 | 35 | ### Recursive Approach 36 | 37 | **Intuition:** The factorial of N can be defined in terms of the factorial of (N - 1): 38 | - N! = N × (N - 1)! 39 | 40 | #### Pseudocode 41 | ``` 42 | function factorial(n): 43 | if n == 0: 44 | return 1 45 | return n * factorial(n - 1) 46 | ``` 47 | 48 | #### Code (C++) 49 | ```cpp 50 | #include 51 | using namespace std; 52 | 53 | int factorial(int n) { 54 | if (n == 0) return 1; // Base case 55 | return n * factorial(n - 1); // Recursive call 56 | } 57 | 58 | int main() { 59 | int n = 5; 60 | cout << "Factorial: " << factorial(n) << endl; 61 | return 0; 62 | } 63 | ``` 64 | 65 | **Output:** 66 | ``` 67 | Factorial: 120 68 | ``` 69 | 70 | **Complexity Analysis:** 71 | - Time Complexity: `O(N)` where N is the input number. 72 | - Space Complexity: `O(N)` due to the call stack. 73 | 74 | --- 75 | 76 | ## 🧷 Implementations 77 | 78 | ### Java 79 | 80 |
81 | Factorial Using Recursion 82 | 83 | ```java 84 | public class Main { 85 | static int factorial(int n) { 86 | if (n == 0) return 1; // Base case 87 | return n * factorial(n - 1); // Recursive call 88 | } 89 | 90 | public static void main(String[] args) { 91 | int n = 5; 92 | System.out.println("Factorial: " + factorial(n)); 93 | } 94 | } 95 | ``` 96 | 97 |
98 | 99 | ### Python 100 | 101 |
102 | Factorial Using Recursion 103 | 104 | ```python 105 | def factorial(n): 106 | if n == 0: 107 | return 1 # Base case 108 | return n * factorial(n - 1) # Recursive call 109 | 110 | n = 5 111 | print("Factorial:", factorial(n)) 112 | ``` 113 | 114 |
115 | 116 | ### JavaScript 117 | 118 |
119 | Factorial Using Recursion 120 | 121 | ```javascript 122 | function factorial(n) { 123 | if (n === 0) return 1; // Base case 124 | return n * factorial(n - 1); // Recursive call 125 | } 126 | 127 | let n = 5; 128 | console.log("Factorial:", factorial(n)); 129 | ``` 130 | 131 |
132 | 133 | --- 134 | 135 | ## 🧭 Edge Cases to Consider 136 | 137 | * `N = 0` (should return 1) 138 | * Negative numbers (should handle gracefully) 139 | 140 | --- 141 | 142 | ## 🧾 Complexity Summary 143 | 144 | | Approach | Time Complexity | Space Complexity | 145 | | ------------- | --------------- | ---------------- | 146 | | Recursive | `O(N)` | `O(N)` | 147 | 148 | --- 149 | 150 | ## 🙌 Credits 151 | 152 | Special thanks to **Striver** for the comprehensive A2Z DSA Course on TakeUforward. 153 | 154 | --- 155 | 156 | ## 📣 Notes 157 | 158 | * Recursion is a powerful tool but can lead to stack overflow if not handled properly. 159 | * Understanding recursion is crucial for solving complex problems like tree traversals and dynamic programming. 160 | -------------------------------------------------------------------------------- /01_Intro_to_Dsa/Patterns/22_number_pattern.md: -------------------------------------------------------------------------------- 1 | # ✅ Number Pattern 2 | 3 | **Problem Statement:** Given an integer N, print the following pattern: 4 | 5 | --- 6 | 7 | ## 📌 Problem Statement 8 | 9 | Print a number pattern where each row contains increasing numbers starting from 1. 10 | 11 | --- 12 | 13 | ## 🧪 Examples 14 | 15 | ### Example 1: 16 | **Input:** 17 | `N = 3` 18 | **Output:** 19 | ``` 20 | 1 21 | 1 2 22 | 1 2 3 23 | ``` 24 | 25 | ### Example 2: 26 | **Input:** 27 | `N = 5` 28 | **Output:** 29 | ``` 30 | 1 31 | 1 2 32 | 1 2 3 33 | 1 2 3 4 34 | 1 2 3 4 5 35 | ``` 36 | 37 | --- 38 | 39 | ## 💡 Approach 40 | 41 | ### 1) Iterative Approach 42 | 43 | **Intuition:** Use nested loops to print the numbers in the required format. 44 | 45 | #### Pseudocode 46 | ``` 47 | for i from 1 to N: 48 | for j from 1 to i: 49 | print(j, end=" ") 50 | print() 51 | ``` 52 | 53 | #### Code (C++) 54 | ```cpp 55 | #include 56 | using namespace std; 57 | 58 | void printNumberPattern(int n) { 59 | for (int i = 1; i <= n; i++) { 60 | for (int j = 1; j <= i; j++) { 61 | cout << j << " "; 62 | } 63 | cout << endl; 64 | } 65 | } 66 | 67 | int main() { 68 | int n = 5; 69 | printNumberPattern(n); 70 | return 0; 71 | } 72 | ``` 73 | 74 | **Output:** 75 | ``` 76 | 1 77 | 1 2 78 | 1 2 3 79 | 1 2 3 4 80 | 1 2 3 4 5 81 | ``` 82 | 83 | **Complexity Analysis:** 84 | - Time Complexity: `O(N^2)` (due to nested loops) 85 | - Space Complexity: `O(1)` (no extra space used) 86 | 87 | --- 88 | 89 | ## 🧷 Implementations 90 | 91 | ### Java 92 | 93 |
94 | Number Pattern 95 | 96 | ```java 97 | public class Main { 98 | static void printNumberPattern(int n) { 99 | for (int i = 1; i <= n; i++) { 100 | for (int j = 1; j <= i; j++) { 101 | System.out.print(j + " "); 102 | } 103 | System.out.println(); 104 | } 105 | } 106 | 107 | public static void main(String[] args) { 108 | int n = 5; 109 | printNumberPattern(n); 110 | } 111 | } 112 | ``` 113 | 114 |
115 | 116 | ### Python 117 | 118 |
119 | Number Pattern 120 | 121 | ```python 122 | def print_number_pattern(n): 123 | for i in range(1, n + 1): 124 | for j in range(1, i + 1): 125 | print(j, end=" ") 126 | print() 127 | 128 | n = 5 129 | print_number_pattern(n) 130 | ``` 131 | 132 |
133 | 134 | ### JavaScript 135 | 136 |
137 | Number Pattern 138 | 139 | ```javascript 140 | function printNumberPattern(n) { 141 | for (let i = 1; i <= n; i++) { 142 | let row = ""; 143 | for (let j = 1; j <= i; j++) { 144 | row += j + " "; 145 | } 146 | console.log(row); 147 | } 148 | } 149 | 150 | let n = 5; 151 | printNumberPattern(n); 152 | ``` 153 | 154 |
155 | 156 | --- 157 | 158 | ## 🧭 Edge Cases to Consider 159 | 160 | * `N = 0` (should handle gracefully) 161 | * `N = 1` (should print a single number) 162 | 163 | --- 164 | 165 | ## 🧾 Complexity Summary 166 | 167 | | Approach | Time Complexity | Space Complexity | 168 | | ------------- | --------------- | ---------------- | 169 | | Iterative | `O(N^2)` | `O(1)` | 170 | 171 | --- 172 | 173 | ## 🙌 Credits 174 | 175 | Special thanks to **Ayush Pandey** for contributing to this article on TakeUforward. 176 | 177 | --- 178 | 179 | ## 📣 Notes 180 | 181 | * This pattern is a common exercise for beginners to understand nested loops. 182 | * Variations can include different starting numbers or different patterns. 183 | --------------------------------------------------------------------------------