├── .vscode ├── spellright.dict ├── foam.json ├── extensions.json └── settings.json ├── dsa-roadmaps ├── Love Babbar Questions │ ├── Heaps │ │ └── readme.md │ ├── Arrays │ │ ├── readme.md │ │ ├── Cyclically rotate an array by one │ │ │ ├── readme.md │ │ │ ├── rotate array by one.cpp │ │ │ └── solution.cpp │ │ ├── Kadane's Algorithm │ │ │ ├── Solution.java │ │ │ ├── Kadane’s Algorithm.cpp │ │ │ └── Readme.md │ │ ├── Triplet Sum in Array │ │ │ ├── readme.md │ │ │ └── solution.cpp │ │ ├── Common elements │ │ │ └── readme.md │ │ ├── Sort an array of 0s, 1s and 2s │ │ │ ├── Solution.java │ │ │ └── Readme.md │ │ ├── Move all negative elements to end │ │ │ ├── readme.md │ │ │ └── solution.cpp │ │ ├── Smallest subarray with sum greater than x │ │ │ ├── readme.md │ │ │ └── solution.cpp │ │ ├── Median of 2 Sorted Arrays of Different Sizes │ │ │ ├── Solution.java │ │ │ └── Readme.md │ │ └── Union of two arrays │ │ │ ├── readme.md │ │ │ └── solution.cpp │ ├── Graphs │ │ ├── readme.md │ │ ├── DFS of a Graph │ │ │ ├── readme.md │ │ │ └── solution.cpp │ │ ├── BFS of a Graph │ │ │ ├── Solution.java │ │ │ └── Readme.md │ │ ├── Making wired Connections │ │ │ └── solution.cpp │ │ ├── Cheapest Flights Within K Stops │ │ │ └── Readme.md │ │ ├── word Ladder │ │ │ ├── solution.cpp │ │ │ └── Readme.md │ │ ├── flood fill algo │ │ │ └── Readme.md │ │ ├── Clone Graph │ │ │ └── Solution.cpp │ │ └── Snakes and Ladders │ │ │ └── Solution.cpp │ ├── Greedy │ │ ├── readme.md │ │ ├── chocolate distribution problem │ │ │ ├── choco.cpp │ │ │ └── readme.md │ │ ├── Find maximum │ │ │ ├── readme.md │ │ │ └── findMax.cpp │ │ ├── Job Sequencing Problem │ │ │ └── readme.md │ │ ├── Huffman Coding │ │ │ └── readme.md │ │ ├── Activity Selection Problem │ │ │ └── readme.md │ │ └── Shortest Job First │ │ │ └── readme.md │ ├── Strings │ │ ├── readme.md │ │ ├── Reverse a String │ │ │ ├── Solution.java │ │ │ ├── reverse string.cpp │ │ │ └── Readme.md │ │ └── Sentence to Mobile Keypad Equivalent │ │ │ ├── KeypadEqv.cpp │ │ │ └── README.md │ ├── Backtracking │ │ ├── readme.md │ │ ├── N_queens │ │ │ ├── readme.md │ │ │ └── N_queens.cpp │ │ ├── Word break using backtracking │ │ │ ├── readme.cpp │ │ │ └── wb.cpp │ │ ├── Rat in maze problem │ │ │ └── readme.md │ │ └── Printing all solutions in n-queen problems │ │ │ └── readme.md │ ├── Binary trees │ │ ├── readme.md │ │ ├── Height of Binary Tree │ │ │ └── readme.md │ │ ├── Zig Zag Traversal │ │ │ ├── readme.md │ │ │ └── ZigZag.cpp │ │ ├── Level Order Traversal │ │ │ └── readme.md │ │ ├── Top View │ │ │ ├── readme.md │ │ │ └── TopView.cpp │ │ ├── Reverse Level Order Traversal │ │ │ └── readme.md │ │ └── Boundary Traversal │ │ │ ├── BoundaryTraversal.cpp │ │ │ └── readme.md │ ├── Linked List │ │ ├── readme.md │ │ ├── RotateByN │ │ │ ├── readme.md │ │ │ └── RotateDLLbyN.cpp │ │ ├── Middle of Linked List │ │ │ ├── readme.md │ │ │ └── solution.java │ │ ├── Palindrome │ │ │ ├── readme.md │ │ │ └── PlaindromeLL.cpp │ │ ├── Add 1 to a number represented as linked list │ │ │ └── readme.md │ │ ├── SplitList │ │ │ ├── readme.md │ │ │ └── SplitList.cpp │ │ ├── Detect loop in linked list │ │ │ ├── readme.md │ │ │ └── solution.java │ │ ├── MergeKSortedLL │ │ │ ├── MergeKSortedLL.cpp │ │ │ └── readme.md │ │ ├── Remove duplicate element from sorted Linked List │ │ │ └── readme.md │ │ ├── FlattenLL │ │ │ ├── Flatten.cpp │ │ │ └── readme.md │ │ ├── Clone linked list(random pointer) │ │ │ └── solution.java │ │ ├── Intersection of 2 LL │ │ │ ├── readme.md │ │ │ └── Intersectionof2LL.cpp │ │ └── Remove duplicates from an unsorted linked list │ │ │ └── readme.md │ ├── Stacks & Queues │ │ ├── readme.md │ │ ├── Queue From Scratch │ │ │ └── README.md │ │ ├── Reverse First K elements of Queue │ │ │ ├── solution.java │ │ │ └── readme.md │ │ ├── Max Area in Histogram │ │ │ └── readme.md │ │ ├── Special Stack │ │ │ ├── readme.md │ │ │ └── solution.java │ │ └── Parenthesis Checker │ │ │ └── readme.md │ ├── Binary Search Trees │ │ ├── readme.md │ │ ├── Find min and max value in a BST │ │ │ └── readme.md │ │ ├── BST To Sorted List │ │ │ └── README.md │ │ ├── Find a value in BST │ │ │ └── readme.md │ │ └── Deletion of a node in a BST │ │ │ └── readme.md │ ├── Bit Manipulation │ │ ├── readme.md │ │ └── Number of 1 Bits │ │ │ ├── readme.md │ │ │ └── solution.cpp │ ├── Dynamic Programming │ │ ├── readme.md │ │ ├── nCr Bionomial Coefficient │ │ │ ├── readme.md │ │ │ └── nCr.cpp │ │ ├── coin change │ │ │ ├── readme.md │ │ │ └── coinChange.java │ │ └── 0-1 knapsack │ │ │ ├── knapsack.cpp │ │ │ └── readme.md │ ├── Searching & Sorting │ │ ├── readme.md │ │ ├── Subarray with 0 sum │ │ │ ├── Solution.java │ │ │ └── Readme.md │ │ ├── Pair with Given Diffrence │ │ │ ├── readme.md │ │ │ └── Pair with Given Difference.cpp │ │ ├── Majority Element │ │ │ ├── readme.md │ │ │ └── Majority Element.cpp │ │ └── Merge Without Extra Space │ │ │ ├── readme.md │ │ │ └── Merge Without Extra Space.cpp │ ├── readme.md │ └── Matrix │ │ ├── Kth smallest element in row-column wise sorted matrix │ │ └── kthsmallest.cpp │ │ └── Common element in all rows of given matrix │ │ └── commonEle.cpp ├── LeetCode Study Plan │ ├── Algorithms │ │ ├── ALgorithm-1 │ │ │ ├── Day 1 - Binary Search │ │ │ │ ├── readme.md │ │ │ │ ├── 35. Search Insert Position │ │ │ │ │ ├── solution1.py │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ ├── 704. Binary Search │ │ │ │ │ ├── solution1.py │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ └── 278. First Bad Version │ │ │ │ │ ├── solution.cpp │ │ │ │ │ ├── solution1.py │ │ │ │ │ └── readme.md │ │ │ ├── readme.md │ │ │ ├── Day 2 - Two Pointers │ │ │ │ ├── 189. Rotate Array │ │ │ │ │ ├── solution2.py │ │ │ │ │ ├── solution1.py │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ └── 977. Squares of a Sorted Array │ │ │ │ │ ├── solution.cpp │ │ │ │ │ ├── readme.md │ │ │ │ │ ├── solution1.py │ │ │ │ │ └── solution2.py │ │ │ ├── Day 5- Two Pointers │ │ │ │ ├── 876. Middle of the Linked List │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ └── 19. Remove Nth Node From End of List Medium │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ ├── Day 4 - Two Pointers │ │ │ │ ├── 344. Reverse String │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ └── 557. Reverse Words in a String III │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ ├── Day 3 - Two Pointers │ │ │ │ ├── 283. Move Zeros │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ │ └── 167. Two Sum II - Input array is sorted │ │ │ │ │ ├── solution.cpp │ │ │ │ │ └── readme.md │ │ │ └── Day 6- Sliding Window │ │ │ │ ├── 3. Longest Substring Without Repeating Characters │ │ │ │ ├── solution.cpp │ │ │ │ └── readme.md │ │ │ │ └── 567. Permutation in String │ │ │ │ ├── solution.cpp │ │ │ │ └── readme.md │ │ └── Algorithm-2 │ │ │ └── readme.md │ ├── Dynamic Programming │ │ └── readme.md │ ├── Data Structure │ │ ├── Data Structure - 2 │ │ │ ├── readme.md │ │ │ ├── Single Number │ │ │ │ ├── solution.cpp │ │ │ │ └── readme.md │ │ │ ├── Majority Element │ │ │ │ ├── solution.cpp │ │ │ │ └── readme.md │ │ │ └── 3Sum │ │ │ │ ├── readme.md │ │ │ │ └── solution.cpp │ │ └── Data Structure- 1 │ │ │ ├── readme.md │ │ │ ├── Contains Duplicate │ │ │ ├── solution1.py │ │ │ ├── solution.cpp │ │ │ └── readme.md │ │ │ ├── Two Sum │ │ │ ├── solution1.py │ │ │ ├── solution.cpp │ │ │ └── readme.md │ │ │ ├── Merge Sorted Array │ │ │ ├── solution.cpp │ │ │ ├── solution2.py │ │ │ └── solution1.py │ │ │ ├── Maximum Subarray │ │ │ ├── solution1.py │ │ │ ├── solution.cpp │ │ │ └── readme.md │ │ │ ├── Best Time to Buy and Sell Stock │ │ │ ├── solution.cpp │ │ │ └── readme.md │ │ │ ├── Pascal's Triangle │ │ │ ├── readme.md │ │ │ └── solution.cpp │ │ │ ├── Reshape the Matrix │ │ │ ├── solution.cpp │ │ │ └── readme.md │ │ │ └── Intersection of Two Arrays II │ │ │ ├── solution.cpp │ │ │ └── readme.md │ └── readme.md └── Beginners │ ├── Algorithms │ ├── LinkedList Implementation │ │ ├── Readme.md │ │ ├── Stack using LinkedList.c │ │ └── Queue using LinkedList.c │ ├── README.md │ ├── Searching │ │ ├── linearSearch.cpp │ │ ├── recursiveLinearSearch.cpp │ │ ├── interpolationSearch.cpp │ │ └── recursiveBinarySearch.cpp │ ├── Sorting │ │ ├── selection sort.cpp │ │ └── heap_sorting.cpp │ └── Graphs │ │ └── Prims.cpp │ ├── Data Structures │ └── Linked List │ │ ├── 1-to-3-BasicImplementation.md │ │ ├── 4-DeletionByKey.md │ │ ├── 6-DeleteLinkedList.md │ │ ├── 5-DeleteByPosition.md │ │ ├── 7-FindLength.md │ │ ├── 6-DeleteLinkedList.cpp │ │ └── 1-to-3-BasicImplementation.cpp │ ├── Problem Solving │ ├── non divisible subset │ │ └── readme.md │ ├── 3d surface area │ │ ├── readme.md │ │ └── solution.cpp │ ├── Bankers Problem │ │ └── Readme.md │ ├── Electronic Shop │ │ └── Readme.md │ ├── Divisible Sum Pairs │ │ └── readme.md │ ├── towersOfHanoi │ │ ├── towersOfHanoi.c │ │ └── towersofHanoi2.c │ ├── sales by match │ │ └── readme.md │ ├── Cats and a Mouse │ │ └── Readme.md │ ├── Diagonal Difference │ │ └── readme.md │ ├── Staircase │ │ ├── readme.md │ │ └── stair.cpp │ ├── Number line Jumps │ │ └── readme.md │ ├── trapping_water.cpp │ ├── books │ │ └── readme.md │ ├── Drawing Book │ │ └── readme.md │ ├── records │ │ └── readme.md │ ├── Breaking The Records │ │ └── readme.md │ ├── Cormen — The Best Friend Of a Man │ │ └── Cormen — The Best Friend Of a Man.cpp │ ├── T-primes │ │ ├── T-primes.cpp │ │ └── readme.md │ ├── Binary Removals │ │ ├── Binary Removals.cpp │ │ └── readme.md │ ├── plus minus │ │ └── readme.md │ ├── counting_islands_in_graph.cpp │ ├── Counting Valleys │ │ └── Readme.md │ ├── birds │ │ ├── readme.md │ │ └── bird.cpp │ ├── Migratory Birds │ │ ├── readme.md │ │ └── birds.cpp │ └── Knapsack │ │ └── Knapsackgreedy1.cpp │ └── readme.md ├── attachments └── foam-icon.png ├── .foam └── templates │ ├── page-with-metadata.md │ └── your-first-template.md ├── _layouts ├── home.html └── page.html └── assets └── css └── style.scss /.vscode/spellright.dict: -------------------------------------------------------------------------------- 1 | wikilink 2 | spellright 3 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Heaps/readme.md: -------------------------------------------------------------------------------- 1 | ## Heaps -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/readme.md: -------------------------------------------------------------------------------- 1 | ## Arrays -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/readme.md: -------------------------------------------------------------------------------- 1 | ## Graphs -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Greedy/readme.md: -------------------------------------------------------------------------------- 1 | ## Greedy -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Strings/readme.md: -------------------------------------------------------------------------------- 1 | ## Strings -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/readme.md: -------------------------------------------------------------------------------- 1 | # Backtracking -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/readme.md: -------------------------------------------------------------------------------- 1 | ## Binary Trees -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/readme.md: -------------------------------------------------------------------------------- 1 | ## Linked Lists -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Stacks & Queues/readme.md: -------------------------------------------------------------------------------- 1 | ## Stacks and Queues -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary Search Trees/readme.md: -------------------------------------------------------------------------------- 1 | # Binary Search Trees -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Bit Manipulation/readme.md: -------------------------------------------------------------------------------- 1 | ## Bit Manipulation 2 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/readme.md: -------------------------------------------------------------------------------- 1 | ## Dynamic Programming -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/readme.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/readme.md: -------------------------------------------------------------------------------- 1 | # Searching and Sorting 2 | -------------------------------------------------------------------------------- /attachments/foam-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vitspot/dsa-roadmaps/HEAD/attachments/foam-icon.png -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/readme.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/study-plan/algorithm/ -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/Algorithm-2/readme.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/study-plan/algorithm/ -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/LinkedList Implementation/Readme.md: -------------------------------------------------------------------------------- 1 | Linked List Data Structure Implementation 2 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Dynamic Programming/readme.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/study-plan/dynamic-programming/ -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/readme.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/study-plan/data-structure/ -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/readme.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/study-plan/data-structure/ -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/README.md: -------------------------------------------------------------------------------- 1 | ## Algorithms 2 | This repository is a collection of commonly used algorithms in DSA. 3 | -------------------------------------------------------------------------------- /.foam/templates/page-with-metadata.md: -------------------------------------------------------------------------------- 1 | --- 2 | type: feature 3 | keywords: hello world 4 | titile: custom heading 5 | --- 6 | 7 | # Heading -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/1-to-3-BasicImplementation.md: -------------------------------------------------------------------------------- 1 | ## Articles 1 to 3: 2 | 3 | [link to article-1](https://www.geeksforgeeks.org/linked-list-set-1-introduction/) -------------------------------------------------------------------------------- /.vscode/foam.json: -------------------------------------------------------------------------------- 1 | { 2 | "purpose": "this file exists to tell the foam-vscode plugin that it's currently in a foam workspace", 3 | "future": "we may use this for custom configuration" 4 | } 5 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/non divisible subset/readme.md: -------------------------------------------------------------------------------- 1 | Given a set of distinct integers, print the size of a maximal subset of it where the sum of any numbers is not evenly divisible by n. -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/3d surface area/readme.md: -------------------------------------------------------------------------------- 1 | Given the discription of a 3d surface area on a grid, calculate its surface area. 2 | input: for a n*m grid, the height of each cell on the grid is given. -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/4-DeletionByKey.md: -------------------------------------------------------------------------------- 1 | # #4 Deleting a given key in Linked List 2 | 3 | ## Article: 4 | 5 | [link to article](https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/) -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Bankers Problem/Readme.md: -------------------------------------------------------------------------------- 1 | #Bankers Problem 2 | is a problem for allocating resources to processes that are present int the system. 3 | Important concept of Operating System Function. -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Contains Duplicate/solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | return not (len(nums)==len(set(nums))) -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/6-DeleteLinkedList.md: -------------------------------------------------------------------------------- 1 | # #6 Write a function to delete a Linked List 2 | 3 | ## Article: 4 | 5 | [link to article](https://www.geeksforgeeks.org/write-a-function-to-delete-a-linked-list/) -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Stacks & Queues/Queue From Scratch/README.md: -------------------------------------------------------------------------------- 1 | ## Queue from scratch 2 | Supports the following operations: 3 | 1. Enqueue 4 | 2. Dequeue 5 | 3. Display queue 6 | 4. Clear queue 7 | 5. Front of the queue 8 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/5-DeleteByPosition.md: -------------------------------------------------------------------------------- 1 | # #5 Delete a Linked List node at a given position 2 | 3 | ## Article: 4 | 5 | [link to article](https://www.geeksforgeeks.org/delete-a-linked-list-node-at-a-given-position/) -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/7-FindLength.md: -------------------------------------------------------------------------------- 1 | # #7 Find Length of a Linked List (Iterative and Recursive) 2 | 3 | ## Article: 4 | 5 | [link to article](https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/) -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 2 - Two Pointers/189. Rotate Array/solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | k %= len(nums) 4 | nums[:] = nums[-k:] + nums[:-k] 5 | 6 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/readme.md: -------------------------------------------------------------------------------- 1 | ## Extra Questions 2 | 3 | This repository is for beginners who want to contribute. In this you can add any number of question with solution of any topic. 4 | You can add study materials which can help our peers to learn. 5 | 6 | ## Add a minimum of 3 questions with solutions for the PR to be accepted. -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Two Sum/solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | lookup = {} 4 | for i,n in enumerate(nums): 5 | if target-n in lookup: 6 | return [lookup[target-n],i] 7 | lookup[n] = i -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/Single Number/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int n = nums.size(); 5 | int k=0; 6 | for(int i=0;inext) 6 | slow = slow->next, fast = fast->next->next; 7 | return slow; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Merge Sorted Array/solution.cpp: -------------------------------------------------------------------------------- 1 | // solution 1 easy 2 | class Solution 3 | { 4 | public: 5 | void merge(vector &nums1, int m, vector &nums2, int n) 6 | { 7 | 8 | for (int i = 0; i < n; i++) 9 | nums1[m + i] = nums2[i]; 10 | 11 | sort(nums1.begin(), nums1.end()); 12 | } 13 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Merge Sorted Array/solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | del nums1[m:] 7 | nums1 += nums2 8 | nums1.sort() 9 | 10 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Electronic Shop/Readme.md: -------------------------------------------------------------------------------- 1 | A person wants to determine the most expensive computer keyboard and USB drive that can be purchased with a give budget. Given price lists for keyboards and USB drives and a budget, find the cost to buy them. If it is not possible to buy both items, return "-1". 2 | 3 | Returns 4 | 5 | int: the maximum that can be spent, or if it is not possible to buy both items 6 | 7 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Maximum Subarray/solution1.py: -------------------------------------------------------------------------------- 1 | # Kaden's algorithms https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ 2 | class Solution: 3 | def maxSubArray(self, nums: List[int]) -> int: 4 | max_sum = float(-inf) 5 | cur_sum = 0 6 | for n in nums: 7 | cur_sum = max(cur_sum+n,n) 8 | max_sum = max(max_sum,cur_sum) 9 | return max_sum -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/35. Search Insert Position/solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | l,r = 0,len(nums)-1 4 | 5 | while l<=r: 6 | m = (l+r)//2 7 | if nums[m] == target: return m 8 | elif nums[m]& vect) 4 | { 5 | 6 | size_t start =0; 7 | size_t end=vect.size()-1; 8 | while(start sortedSquares(vector& nums) { 6 | for(int i=0;i3 8 | As no trivial solution exists for inputs 1,2 and 3 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/nCr Bionomial Coefficient/readme.md: -------------------------------------------------------------------------------- 1 | Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7. 2 | You do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCr modulo 109+7.. 3 | Expected Time Complexity: O(n*r) 4 | Expected Auxiliary Space: O(r) 5 | 6 | 7 | Constraints: 8 | 1 ≤ n ≤ 1000 9 | 1 ≤ r ≤ 800 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Best Time to Buy and Sell Stock/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | 7 | int profitmax = 0, profitmin = prices[0]; 8 | for (int i = 0; i < prices.size(); i++) 9 | { 10 | profitmax = max(profitmax, prices[i] - profitmin); 11 | profitmin = min(profitmin, prices[i]); 12 | } 13 | return profitmax; 14 | } 15 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 2 - Two Pointers/189. Rotate Array/solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | def helper(i,j,nums): 4 | while(i& nums) { 4 | // KAdane's Algo 5 | // morgan stanley 2021 6 | int maxSum = nums[0]; 7 | int presSum = maxSum; 8 | for(int i=1;i& nums, int k) { 6 | if(k%nums.size()!=0) { 7 | k=k%nums.size();k=nums.size()-k; 8 | reverse(nums.begin(),nums.begin()+k); 9 | reverse(nums.begin()+k,nums.end()); 10 | reverse(nums.begin(),nums.end()); 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/coin change/readme.md: -------------------------------------------------------------------------------- 1 | Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. 2 | 3 | You don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents. 4 | 5 | 6 | Expected Time Complexity: O(m*n). 7 | Expected Auxiliary Space: O(n). -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/nCr Bionomial Coefficient/nCr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binomialCoeff(int n, int k) 5 | { 6 | if (k > n) 7 | return 0; 8 | if (k == 0 || k == n) 9 | return 1; 10 | 11 | return binomialCoeff(n - 1, k - 1) 12 | + binomialCoeff(n - 1, k); 13 | } 14 | 15 | 16 | int main() 17 | { 18 | int n = 5, k = 2; 19 | cout << "Value of C(" << n << ", " << k << ") is " 20 | << binomialCoeff(n, k); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Strings/Reverse a String/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | // Complete the function 4 | // str: input string 5 | public static String reverseWord(String str) 6 | { 7 | char[] s= str.toCharArray(); 8 | for(int i=0; i& nums) { 6 | int j = 0; 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (nums[i] != 0) { 9 | nums[j++] = nums[i]; 10 | } 11 | } 12 | for (;j < nums.size(); j++) { 13 | nums[j] = 0; 14 | } 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | // Foam's own extension 6 | "foam.foam-vscode", 7 | 8 | // Tons of markdown goodies (lists, tables of content, so much more) 9 | "yzhang.markdown-all-in-one", 10 | 11 | // Image-pasting for markdown 12 | "mushan.vscode-paste-image", 13 | 14 | // Spell checking for text, markdown and latex 15 | "ban.spellright", 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /_layouts/home.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: default 3 | --- 4 | 5 | {{ content }} 6 | 7 | 19 | -------------------------------------------------------------------------------- /_layouts/page.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: default 3 | --- 4 | 5 | {{ content }} 6 | 7 | 19 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Contains Duplicate/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | if (nums == null || nums.length == 0) return false; 4 | 5 | Set setmade = new HashSet<>(); 6 | int l = nums.length; 7 | for (int i=0; inext; 7 | } 8 | while(t2->next != NULL) { 9 | t1 = &((*t1)->next); 10 | t2 = t2->next; 11 | } 12 | *t1 = (*t1)->next; 13 | return head; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Strings/Reverse a String/reverse string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n,i; 6 | char temp; 7 | string a; 8 | cout<<"Enter the string:"; 9 | cin>>a; 10 | n=a.length(); 11 | 12 | for(i=0; i int: 3 | n = len(nums) 4 | l,r = 0,n-1 5 | 6 | while l 2 | int move(int fr, int to); 3 | int towers(int n,int fr, int to,int spare); 4 | int main() 5 | { 6 | towers(4,1,2,3); 7 | } 8 | int move(int fr,int to) 9 | { 10 | printf("move from tower %d to tower %d\n",fr,to); 11 | } 12 | int towers(int n,int fr, int to,int spare) 13 | { 14 | if(n==1) 15 | { 16 | move(fr,to); 17 | } 18 | else{ 19 | towers(n-1,fr,spare,to); 20 | towers(1,fr,to,spare); 21 | towers(n-1,spare,to,fr); 22 | } 23 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Pascal's Triangle/readme.md: -------------------------------------------------------------------------------- 1 | ## Pascal's Triangle 2 | 3 | Given an integer numRows, return the first numRows of Pascal's triangle. 4 | 5 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 6 | 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: numRows = 5 13 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 14 | 15 | Example 2: 16 | 17 | Input: numRows = 1 18 | Output: [[1]] 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= numRows <= 30 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Middle of Linked List/readme.md: -------------------------------------------------------------------------------- 1 | ## Problem statement 2 | Given the head of a singly linked list, return the middle node of the linked list. 3 | If there are two middle nodes, return the second middle node. 4 | 5 | ## Example 6 | ``` 7 | Input: head = [1,2,3,4,5] 8 | Output: [3,4,5] 9 | Explanation: The middle node of the list is node 3. 10 | ``` 11 | ``` 12 | Input: head = [1,2,3,4,5,6] 13 | Output: [4,5,6] 14 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 15 | ``` 16 | 17 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Palindrome/readme.md: -------------------------------------------------------------------------------- 1 | Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not. 2 | 3 | Example 1: 4 | 5 | Input: 6 | N = 3 7 | value[] = {1,2,1} 8 | Output: 1 9 | Explanation: The given linked list is 10 | 1 2 1 , which is a palindrome and 11 | Hence, the output is 1. 12 | Example 2: 13 | 14 | Input: 15 | N = 4 16 | value[] = {1,2,3,4} 17 | Output: 0 18 | Explanation: The given linked list 19 | is 1 2 3 4 , which is not a palindrome 20 | and Hence, the output is 0. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/Subarray with 0 sum/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | //Function to check whether there is a subarray present with 0-sum or not. 3 | static boolean findsum(int arr[],int n) 4 | { 5 | HashMap hm= new HashMap(); 6 | int sum= 0; 7 | for(int i=0; i5->6 12 | Output: 457 13 | ``` 14 | 15 | Example 2: 16 | ```C 17 | Input: 18 | LinkedList: 1->2->3 19 | Output: 124 20 | ``` 21 | Expected Time Complexity: O(N). 22 | Expected Auxiliary Space: O(1). 23 | 24 | Constraints: 25 | 1 <= N <= 10^1000 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 3 - Two Pointers/167. Two Sum II - Input array is sorted/solution.cpp: -------------------------------------------------------------------------------- 1 | //O(log n) Time Complexity 2 | //O(1) Space Complexity 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& numbers, int target) { 7 | int lo=0, hi=numbers.size()-1; 8 | while (numbers[lo]+numbers[hi]!=target){ 9 | if (numbers[lo]+numbers[hi]({lo+1,hi+1}); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 6- Sliding Window/3. Longest Substring Without Repeating Characters/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | #define max(a, b) (a < b ? b : a) 3 | public: 4 | int lengthOfLongestSubstring(string s) { 5 | vector dict(256, -1); 6 | int maxLen = 0, start = -1; 7 | for (int i = 0; i != s.length(); i++) { 8 | if (dict[s[i]] > start) 9 | start = dict[s[i]]; 10 | dict[s[i]] = i; 11 | maxLen = max(maxLen, i - start); 12 | } 13 | return maxLen; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Pascal's Triangle/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> generate(int numRows) 5 | { 6 | 7 | vector> addin(numRows); 8 | for (auto i = 0; i < numRows; i++) 9 | { 10 | addin[i].resize(i + 1); 11 | addin[i][0] = addin[i][i] = 1; 12 | 13 | for (auto j = 1; j < i; j++) 14 | { 15 | addin[i][j] = addin[i - 1][j - 1] + addin[i - 1][j]; 16 | } 17 | } 18 | return addin; 19 | } 20 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Cyclically rotate an array by one/readme.md: -------------------------------------------------------------------------------- 1 | ## Cyclically rotate an array by one 2 | 3 | 4 | Given an array, rotate the array by one position in clock-wise direction. 5 | 6 | 7 | 8 | Example 1: 9 | ```C 10 | Input: 11 | N = 5 12 | A[] = {1, 2, 3, 4, 5} 13 | Output: 14 | 5 1 2 3 4 15 | ``` 16 | 17 | Example 2: 18 | ```C 19 | Input: 20 | N = 8 21 | A[] = {9, 8, 7, 6, 4, 2, 1, 3} 22 | Output: 23 | 3 9 8 7 6 4 2 1 24 | ``` 25 | 26 | 27 | Expected Time Complexity: O(N) 28 | Expected Auxiliary Space: O(1) 29 | 30 | Constraints: 31 | 1<=N<=10^5 32 | 0<=a[i]<=10^5 33 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/SplitList/readme.md: -------------------------------------------------------------------------------- 1 | Given a Cirular Linked List of size N, split it into two halves circular lists. If there are odd number of nodes in the given circular linked list then out of the resulting two halved lists, first list should have one node more than the second list. The resultant lists should also be circular lists and not linear lists. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | Circular LinkedList: 1->5->7 9 | Output: 10 | 1 5 11 | 7 12 | 13 | 14 | Example 2: 15 | 16 | Input: 17 | Circular LinkedList: 2->6->1->5 18 | Output: 19 | 2 6 20 | 1 5 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Zig Zag Traversal/readme.md: -------------------------------------------------------------------------------- 1 | Given a Binary Tree. Find the Zig-Zag Level Order Traversal of the Binary Tree. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | 3 9 | / \ 10 | 2 1 11 | Output: 12 | 3 1 2 13 | 14 | Example 2: 15 | 16 | Input: 17 | 7 18 | / \ 19 | 9 7 20 | / \ / 21 | 8 8 6 22 | / \ 23 | 10 9 24 | Output: 25 | 7 7 9 8 8 6 9 10 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 4 - Two Pointers/344. Reverse String/readme.md: -------------------------------------------------------------------------------- 1 | ## Reverse String 2 | ### Problem Statement 3 | Write a function that reverses a string. The input string is given as an array of characters s. 4 | 5 | 6 | 7 | 8 | Example 1: 9 | ``` 10 | Input: s = ["h","e","l","l","o"] 11 | Output: ["o","l","l","e","h"] 12 | 13 | ``` 14 | 15 | Example 2: 16 | ``` 17 | Input: s = ["H","a","n","n","a","h"] 18 | Output: ["h","a","n","n","a","H"] 19 | ``` 20 | 21 | Constraints: 22 | ``` 23 | 1 <= s.length <= 105 24 | s[i] is a printable ascii character. 25 | ``` 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Cyclically rotate an array by one/rotate array by one.cpp: -------------------------------------------------------------------------------- 1 | # include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cout << "Enter limit: "; 8 | cin>>n; 9 | int a[n]; 10 | for (int i = 0; i < n; i++) { 11 | cin >> a[i]; 12 | } 13 | 14 | int m = sizeof(a) / sizeof(a[0]); 15 | 16 | int x = a[m - 1], i; 17 | for (i = m - 1; i > 0; i--) 18 | a[i] = a[i - 1]; 19 | a[0] = x; 20 | 21 | for (i = 0; i < n; i++){ 22 | cout << a[i]; 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Bit Manipulation/Number of 1 Bits/readme.md: -------------------------------------------------------------------------------- 1 | ## Number of 1 Bits 2 | Given a positive integer N, print count of set bits in it. 3 | 4 | 5 | 6 | Example 1: 7 | ```C 8 | Input: 9 | N = 6 10 | Output: 11 | 2 12 | Explanation: 13 | Binary representation is '110' 14 | So the count of the set bit is 2. 15 | ``` 16 | 17 | Example 2: 18 | ```C 19 | Input: 20 | 8 21 | Output: 22 | 1 23 | Explanation: 24 | Binary representation is '1000' 25 | So the count of the set bit is 1. 26 | ``` 27 | Expected Time Complexity: O(LogN) 28 | Expected Auxiliary Space: O(1) 29 | 30 | Constraints: 31 | 1 ≤ N ≤ 109 32 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/sales by match/readme.md: -------------------------------------------------------------------------------- 1 | There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. 2 | 3 | Example 4 | 5 | 6 | There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . 7 | 8 | Function Description 9 | 10 | Complete the sockMerchant function in the editor below. 11 | 12 | sockMerchant has the following parameter(s): 13 | 14 | int n: the number of socks in the pile 15 | int ar[n]: the colors of each sock -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/278. First Bad Version/solution1.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return an integer 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | l,r = 1,n 13 | 14 | while l<=r: 15 | m = (l+r)//2 16 | if isBadVersion(m): 17 | r = m-1 18 | else: 19 | l = m+1 20 | 21 | return l -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Contains Duplicate/readme.md: -------------------------------------------------------------------------------- 1 | ## Contains Duplicate 2 | 3 | Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 4 | 5 | Example 1: 6 | 7 | Input: nums = [1,2,3,1] 8 | Output: true 9 | 10 | Example 2: 11 | 12 | Input: nums = [1,2,3,4] 13 | Output: false 14 | 15 | Example 3: 16 | 17 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 18 | Output: true 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= nums.length <= 105 24 | -109 <= nums[i] <= 109 -------------------------------------------------------------------------------- /assets/css/style.scss: -------------------------------------------------------------------------------- 1 | --- 2 | --- 3 | 4 | @import "{{ site.theme }}"; 5 | 6 | .markdown-body { 7 | max-width: 800px; 8 | font-size: 16px; 9 | } 10 | 11 | .markdown-body p { 12 | font-size: 16px; 13 | line-height: 1.9em; 14 | margin-bottom: 1.2em; 15 | } 16 | 17 | .markdown-body li { 18 | line-height: 1.9em; 19 | } 20 | 21 | input.task-list-item-checkbox { 22 | margin-right: 4px; 23 | } 24 | 25 | h1, 26 | h2, 27 | h3, 28 | h4, 29 | h5, 30 | blockquote { 31 | font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, 32 | "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif; 33 | } 34 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 4 - Two Pointers/557. Reverse Words in a String III/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | int k = 0; 5 | s += " "; 6 | string ans = ""; 7 | for(int i = 0; i < s.size(); i++) { 8 | if(s[i] == ' ') { 9 | string word = s.substr(k,i-k); 10 | reverse(word.begin(), word.end()); 11 | ans = ans + word; 12 | if(i != s.size()-1) ans+=" "; 13 | k = i+1; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Kadane's Algorithm/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | // arr: input array 4 | // n: size of array 5 | //Function to find the sum of contiguous subarray with maximum sum. 6 | int maxSubarraySum(int arr[], int n){ 7 | 8 | int max= Integer.MIN_VALUE; 9 | int positiveSum= 0; 10 | 11 | for(int i=0; i 0) 9 | count_chars--; 10 | if(count_chars == 0) return true; 11 | if(j - i == s1.size() && map[s2.at(i++) - 'a']++ >= 0) 12 | count_chars++; 13 | } 14 | return false; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/Word break using backtracking/readme.cpp: -------------------------------------------------------------------------------- 1 | Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences. 2 | Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list. 3 | 4 | Expected Time Complexity: O(N2*n) where N = |s| 5 | Expected Auxiliary Space: O(N2) 6 | 7 | Constraints: 8 | 1 ≤ n ≤ 20 9 | 1 ≤ dict[i] ≤ 15 10 | 1 ≤ |s| ≤ 500 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/Majority Element/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int majorityElement(vector& nums) 5 | { 6 | int n=nums.size(); 7 | 8 | int c=0; 9 | int count=0; 10 | 11 | for(auto i:nums) 12 | { 13 | if(count==0) 14 | { 15 | c=i; 16 | } 17 | if(c==i) 18 | { 19 | count++; 20 | } 21 | else 22 | { 23 | count--; 24 | } 25 | } 26 | return c; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Stacks & Queues/Reverse First K elements of Queue/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to reverse first k elements of a queue. 3 | public Queue modifyQueue(Queue q, int k) { 4 | Stack stack=new Stack<>(); 5 | for(int i=0;i queue=new LinkedList<>(); 10 | while(!stack.isEmpty()){ 11 | queue.add(stack.pop()); 12 | } 13 | while(!q.isEmpty()){ 14 | queue.add(q.poll()); 15 | } 16 | return queue; 17 | } 18 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Searching/linearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { 4 | int a[10] = {10, 23, 40, 1, 2, 0, 14, 13, 50, 9}; 5 | int item, i, flag; 6 | printf("\nEnter Item which is to be searched\n"); 7 | scanf("%d", &item); 8 | for (i = 0; i < 10; i++) 9 | { 10 | if (a[i] == item) 11 | { 12 | flag = i + 1; 13 | break; 14 | } 15 | else 16 | flag = 0; 17 | } 18 | if (flag != 0) 19 | { 20 | printf("\nItem found at location %d\n", flag); 21 | } 22 | else 23 | { 24 | printf("\nItem not found\n"); 25 | } 26 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/3Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## 3Sum 2 | 3 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 4 | 5 | Notice that the solution set must not contain duplicate triplets. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [-1,0,1,2,-1,-4] 12 | Output: [[-1,-1,2],[-1,0,1]] 13 | 14 | Example 2: 15 | 16 | Input: nums = [] 17 | Output: [] 18 | 19 | Example 3: 20 | 21 | Input: nums = [0] 22 | Output: [] 23 | 24 | 25 | Constraints: 26 | 27 | 0 <= nums.length <= 3000 28 | -105 <= nums[i] <= 105 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Level Order Traversal/readme.md: -------------------------------------------------------------------------------- 1 | Given a binary tree, find its level order traversal. 2 | Level order traversal of a tree is breadth-first traversal for the tree. 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | 1 9 | / \ 10 | 3 2 11 | Output:1 3 2 12 | Example 2: 13 | 14 | Input: 15 | 10 16 | / \ 17 | 20 30 18 | / \ 19 | 40 60 20 | Output:10 20 30 40 60 N N 21 | 22 | Your Task: 23 | You don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree. 24 | 25 | 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Detect loop in linked list/readme.md: -------------------------------------------------------------------------------- 1 | ## Problem statement 2 | Given a linked list of N nodes. The task is to check if the linked list has a loop. Linked list can contain self loop. 3 | 4 | ## Example 5 | ``` 6 | Input: 7 | N = 3 8 | value[] = {1,3,4} 9 | x = 2 10 | Output: True 11 | Explanation: In above test case N = 3. 12 | The linked list with nodes N = 3 is 13 | given. Then value of x=2 is given which 14 | means last node is connected with xth 15 | node of linked list. Therefore, there 16 | exists a loop. 17 | ``` 18 | ``` 19 | Input: 20 | N = 4 21 | value[] = {1,8,3,4} 22 | x = 0 23 | Output: False 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Detect loop in linked list/solution.java: -------------------------------------------------------------------------------- 1 | /* Node is defined as 2 | class Node 3 | { 4 | int data; 5 | Node next; 6 | Node(int d) {data = d; next = null; } 7 | } 8 | */ 9 | class Solution { 10 | //Function to check if the linked list has a loop. 11 | public static boolean detectLoop(Node head){ 12 | HashMap map=new HashMap<>(); 13 | Node temp=head; 14 | while(temp!=null){ 15 | if(map.containsKey(temp)) 16 | return true; 17 | else map.put(temp,0); 18 | temp=temp.next; 19 | } 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Two Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | map map; 5 | vector v; 6 | for(int i=0;i> matrixReshape(vector> &mat, int r, int c) 5 | { 6 | 7 | if (mat.empty()) 8 | return mat; 9 | 10 | int m = mat.size(); 11 | int n = mat[0].size(); 12 | 13 | if (m * n < r * c) 14 | return mat; 15 | if (m * n > r * c) 16 | return mat; 17 | 18 | vector> newmat(r, vector(c)); 19 | for (int i = 0; i < r * c; i++) 20 | { 21 | newmat[i / c][i % c] = mat[i / n][i % n]; 22 | } 23 | return newmat; 24 | } 25 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Kadane's Algorithm/Kadane’s Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cout << "Enter limit: "; 9 | cin>>n; 10 | int a[n]; 11 | for (int i = 0; i < n; i++) { 12 | cin >> a[i]; 13 | } 14 | int m = sizeof(a)/sizeof(a[0]); 15 | 16 | int max1=INT_MIN, max2 = 0; // Remember 17 | 18 | for (int i = 0; i < s; i++) 19 | { 20 | max2 = max2 + a[i]; 21 | if (max1 < max2) 22 | max1 = max2; 23 | 24 | if (max2 < 0) 25 | max2 = 0; 26 | } 27 | cout << max1; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary Search Trees/Find min and max value in a BST/readme.md: -------------------------------------------------------------------------------- 1 | Given a Binary Search Tree. The task is to find the minimum element in this given BST. 2 | 3 | Example 1: 4 | 5 | Input: 6 | 5 7 | / \ 8 | 4 6 9 | / \ 10 | 3 7 11 | / 12 | 1 13 | Output: 1 14 | Example 2: 15 | 16 | Input: 17 | 9 18 | \ 19 | 10 20 | \ 21 | 11 22 | Output: 9 23 | Your Task: 24 | The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum elemnt, so retutn -1 in that case. -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/Majority Element/readme.md: -------------------------------------------------------------------------------- 1 | ## Majority Element 2 | 3 | Given an array nums of size n, return the majority element. 4 | 5 | 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. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [3,2,3] 12 | Output: 3 13 | Example 2: 14 | 15 | Example 2: 16 | 17 | Input: nums = [2,2,1,1,1,2,2] 18 | Output: 2 19 | 20 | 21 | Constraints: 22 | 23 | n == nums.length 24 | 1 <= n <= 5 * 104 25 | -231 <= nums[i] <= 231 - 1 26 | 27 | 28 | Follow-up: Could you solve the problem in linear time and in O(1) space? 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Sorting/selection sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string a; 7 | int n,i, j, m, temp; 8 | cout<<"Enter the string :"; 9 | cin>>a; 10 | n=a.length(); 11 | for (i = 0; i < n - 1; i++) { 12 | m = i; 13 | for (j = i + 1; j < n; j++) 14 | if (a[j] < a[m]) 15 | m = j; 16 | if (m != i) { 17 | temp = a[i]; 18 | a[i] = a[m]; 19 | a[m] = temp; 20 | } 21 | } 22 | 23 | cout<<"sorted string:"; 24 | for(i=0;i<=n;i++) 25 | cout<& nums, int target) { 4 | if(target > nums[nums.size()-1]){ 5 | return nums.size(); 6 | } 7 | int l = 0, r = nums.size()-1; 8 | int mid; 9 | while(r > l) { 10 | mid = l + (r - l) / 2; 11 | 12 | if(nums[mid] == target) 13 | return mid; 14 | 15 | if(nums[mid] > target){ 16 | r = mid; 17 | } else { 18 | l = mid + 1; 19 | } 20 | } 21 | 22 | return l; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Triplet Sum in Array/readme.md: -------------------------------------------------------------------------------- 1 | ## Triplet Sum in Array 2 | 3 | Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X. 4 | 5 | 6 | Example 1: 7 | ```C 8 | Input: 9 | n = 6, X = 13 10 | arr[] = [1 4 45 6 10 8] 11 | Output: 12 | 1 13 | Explanation: 14 | The triplet {1, 4, 8} in 15 | the array sums up to 13. 16 | ``` 17 | Example 2: 18 | ```C 19 | Input: 20 | n = 5, X = 10 21 | arr[] = [1 2 4 3 6] 22 | Output: 23 | 1 24 | Explanation: 25 | The triplet {1, 3, 6} in 26 | the array sums up to 10. 27 | ``` 28 | 29 | Expected Time Complexity: O(n^2) 30 | Expected Auxiliary Space: O(1) 31 | 32 | Constraints: 33 | 1 ≤ n ≤ 10^3 34 | 1 ≤ A[i] ≤ 10^5 35 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/towersOfHanoi/towersofHanoi2.c: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void towerOfHanoi(int n, char from_rod, 5 | char to_rod, char aux_rod) 6 | { 7 | if (n == 1) 8 | { 9 | cout << "Move disk 1 from rod " << from_rod << 10 | " to rod " << to_rod< s) 3 | { 4 | s.push(a); 5 | } 6 | public int pop(Stack s) 7 | { 8 | return s.pop(); 9 | } 10 | public int min(Stack s) 11 | { 12 | int min=s.peek(); 13 | for(int i=0;is.get(i)) min=s.get(i); 15 | } 16 | return min; 17 | } 18 | public boolean isFull(Stacks, int n) 19 | { 20 | if(s.size()==n) return true; 21 | else return false; 22 | } 23 | public boolean isEmpty(Stacks) 24 | { 25 | if(s.size()==0) return true; 26 | else return false; 27 | } 28 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 6- Sliding Window/567. Permutation in String/readme.md: -------------------------------------------------------------------------------- 1 | ## Permutation in String 2 | ### Problem Statement 3 | Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. 4 | 5 | In other words, return true if one of s1's permutations is the substring of s2. 6 | 7 | 8 | 9 | 10 | Example 1: 11 | ``` 12 | Input: s1 = "ab", s2 = "eidbaooo" 13 | Output: true 14 | Explanation: s2 contains one permutation of s1 ("ba"). 15 | 16 | ``` 17 | 18 | Example 2: 19 | ``` 20 | Input: s1 = "ab", s2 = "eidboaoo" 21 | Output: false 22 | ``` 23 | 24 | Constraints: 25 | ``` 26 | 1 <= s1.length, s2.length <= 104 27 | s1 and s2 consist of lowercase English letters. 28 | ``` 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Common elements/readme.md: -------------------------------------------------------------------------------- 1 | ## Common elements 2 | 3 | Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. 4 | Note: can you take care of the duplicates without using any additional Data Structure? 5 | 6 | 7 | 8 | Example 1: 9 | ```C 10 | Input: 11 | n1 = 6; A = {1, 5, 10, 20, 40, 80} 12 | n2 = 5; B = {6, 7, 20, 80, 100} 13 | n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120} 14 | Output: 20 80 15 | Explanation: 20 and 80 are the only 16 | common elements in A, B and C. 17 | ``` 18 | 19 | Expected Time Complexity: O(n1 + n2 + n3) 20 | Expected Auxiliary Space: O(n1 + n2 + n3) 21 | 22 | Constraints: 23 | 1 <= n1, n2, n3 <= 10^5 24 | The array elements can be both positive or negative integers. 25 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Sort an array of 0s, 1s and 2s/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static void swap(int a[], int i, int j) { 4 | int temp= a[i]; 5 | a[i]= a[j]; 6 | a[j]= temp; 7 | } 8 | 9 | public static void sort012(int a[], int n) 10 | { 11 | int l= 0; 12 | int r= n-1; 13 | 14 | int i= 0; 15 | 16 | while(i<=r) { 17 | if(a[i]==0) { 18 | swap(a, i, l); 19 | l++; 20 | } 21 | else if(a[i]==2) { 22 | swap(a, i, r); 23 | r--; 24 | continue; 25 | } 26 | i++; 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/0-1 knapsack/knapsack.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int max(int a, int b) { return (a > b) ? a : b; } 6 | 7 | int knapSack(int W, int wt[], int val[], int n) 8 | { 9 | 10 | if (n == 0 || W == 0) 11 | return 0; 12 | 13 | if (wt[n - 1] > W) 14 | return knapSack(W, wt, val, n - 1); 15 | 16 | 17 | else 18 | return max( 19 | val[n - 1] 20 | + knapSack(W - wt[n - 1], 21 | wt, val, n - 1), 22 | knapSack(W, wt, val, n - 1)); 23 | } 24 | 25 | 26 | int main() 27 | { 28 | int val[] = { 60, 100, 120 }; 29 | int wt[] = { 10, 20, 30 }; 30 | int W = 50; 31 | int n = sizeof(val) / sizeof(val[0]); 32 | cout << knapSack(W, wt, val, n); 33 | return 0; 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/Pair with Given Diffrence/readme.md: -------------------------------------------------------------------------------- 1 | Given an array Arr[] of size L and a number N, you need to write a program to find if there exists a pair of elements in the array whose difference is N. 2 | 3 | Example 1: 4 | 5 | Input: 6 | L = 6, N = 78 7 | arr[] = {5, 20, 3, 2, 5, 80} 8 | Output: 1 9 | Explanation: (2, 80) have difference of 78. 10 | Example 2: 11 | 12 | Input: 13 | L = 5, N = 45 14 | arr[] = {90, 70, 20, 80, 50} 15 | Output: -1 16 | Explanation: There is no pair with difference of 45. 17 | Your Task: 18 | You need not take input or print anything. Your task is to complete the function findPair() which takes array arr, size of the array L and N as input parameters and returns True if required pair exists, else return False. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Bit Manipulation/Number of 1 Bits/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution { 6 | public: 7 | int setBits(int n) { 8 | int c=0; 9 | while(n) 10 | { 11 | if(n%2!=0) 12 | c++; 13 | n = n/2; 14 | 15 | } 16 | return c; 17 | // Write Your Code here 18 | } 19 | }; 20 | 21 | // { Driver Code Starts. 22 | int main() { 23 | int t; 24 | cin >> t; 25 | while (t--) { 26 | int N; 27 | cin >> N; 28 | 29 | Solution ob; 30 | int cnt = ob.setBits(N); 31 | cout << cnt << endl; 32 | } 33 | return 0; 34 | } 35 | // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Move all negative elements to end/readme.md: -------------------------------------------------------------------------------- 1 | ## Move all negative elements to end 2 | 3 | Given an unsorted array arr[] of size N having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element. 4 | 5 | 6 | 7 | Example 1: 8 | ```C 9 | Input : 10 | N = 8 11 | arr[] = {1, -1, 3, 2, -7, -5, 11, 6 } 12 | Output : 13 | 1 3 2 11 6 -1 -7 -5 14 | ``` 15 | 16 | Example 2: 17 | ```C 18 | Input : 19 | N=8 20 | arr[] = {-5, 7, -3, -4, 9, 10, -1, 11} 21 | Output : 22 | 7 9 10 11 -5 -3 -4 -1 23 | ``` 24 | Expected Time Complexity: O(N) 25 | Expected Auxiliary Space: O(N) 26 | 27 | Constraints: 28 | 1 ≤ N ≤ 10^5 29 | -10^5 ≤ arr[] ≤ 10^5 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/Majority Element/readme.md: -------------------------------------------------------------------------------- 1 | Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array. 2 | 3 | 4 | Example 1: 5 | 6 | Input: 7 | N = 3 8 | A[] = {1,2,3} 9 | Output: 10 | -1 11 | Explanation: 12 | Since, each element in 13 | {1,2,3} appears only once so there 14 | is no majority element. 15 | Example 2: 16 | 17 | Input: 18 | N = 5 19 | A[] = {3,1,3,3,2} 20 | Output: 21 | 3 22 | Explanation: 23 | Since, 3 is present more 24 | than N/2 times, so it is 25 | the majority element. 26 | 27 | Your Task: 28 | The task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/readme.md: -------------------------------------------------------------------------------- 1 | ## Love Babbar 450 ques 2 | 3 | It is a collection of 450 questions related to data structures and algorithms. The questions are from various DSA topics like Array, Strings, Graph, Trees, Linked list, stack and queue, etc. 4 | 5 | The list is created by Love Babbar. The questions have been curated from reputed websites like geekforgeeks, leetcode, codechef, etc. 6 | 7 | ### Link for 450 Questions - [Click Here](https://docs.google.com/spreadsheets/d/1FMdN_OCfOI0iAeDlqswCiC2DZzD4nPsb/edit) 8 | 9 | Make a copy of the questions in your system. 10 | You can click on the question to view the full question in Geeksforgeeks or Leetcode. You can also mark the question as solved or unsolved in the sheet itself. 11 | 12 | ### Add a minimum of 3 questions for the PR to be accepted -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Cats and a Mouse/Readme.md: -------------------------------------------------------------------------------- 1 | Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse does not move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight. 2 | 3 | You are given queries in the form of , , and representing the respective positions for cats and , and for mouse . Complete the function to return the appropriate answer to each query, which will be printed on a new line. 4 | If cat catches the mouse first, print Cat A. 5 | If cat catches the mouse first, print Cat B. 6 | If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Top View/readme.md: -------------------------------------------------------------------------------- 1 | Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree 2 | 3 | 1 4 | / \ 5 | 2 3 6 | / \ / \ 7 | 4 5 6 7 8 | 9 | Top view will be: 4 2 1 3 7 10 | Note: Return nodes from leftmost node to rightmost node. 11 | 12 | Example 1: 13 | 14 | Input: 15 | 1 16 | / \ 17 | 2 3 18 | Output: 2 1 3 19 | 20 | Example 2: 21 | 22 | Input: 23 | 10 24 | / \ 25 | 20 30 26 | / \ / \ 27 | 40 60 90 100 28 | Output: 40 20 10 30 100 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/704. Binary Search/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int binarySearch(vector& arr, int l, int r, int t){ 4 | if(r >= l){ 5 | int mid = l + (r-l) / 2; 6 | if(arr[mid] == t){ 7 | return mid; 8 | } 9 | 10 | if(arr[mid] > t){ 11 | return binarySearch(arr, l, mid-1, t); 12 | } else { 13 | return binarySearch(arr, mid+1,r, t); 14 | } 15 | 16 | } 17 | return -1; 18 | } 19 | int search(vector& nums, int target) { 20 | int l = 0; 21 | int r = nums.size()-1; 22 | 23 | return binarySearch(nums, l, r, target); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 2 - Two Pointers/977. Squares of a Sorted Array/readme.md: -------------------------------------------------------------------------------- 1 | ## Squares of a Sorted Array 2 | ### Problem Statement 3 | Given an integer array nums sorted in non-decreasing order. 4 | 5 | Return an array of the squares of each number sorted in non-decreasing order. 6 | 7 | 8 | 9 | 10 | Example 1: 11 | ``` 12 | Input: nums = [-4,-1,0,3,10] 13 | Output: [0,1,9,16,100] 14 | Explanation: After squaring, the array becomes [16,1,0,9,100]. 15 | After sorting, it becomes [0,1,9,16,100]. 16 | ``` 17 | 18 | Example 2: 19 | ``` 20 | Input: nums = [-7,-3,2,3,11] 21 | Output: [4,9,9,49,121 22 | ``` 23 | 24 | Constraints: 25 | ``` 26 | 1 <= nums.length <= 104 27 | -104 <= nums[i] <= 104 28 | nums is sorted in non-decreasing order. 29 | ``` 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure - 2/Single Number/readme.md: -------------------------------------------------------------------------------- 1 | ## Single Number 2 | 3 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 4 | 5 | You must implement a solution with a linear runtime complexity and use only constant extra space. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [2,2,1] 12 | Output: 1 13 | Example 2: 14 | 15 | Example 2: 16 | 17 | Input: nums = [4,1,2,1,2] 18 | Output: 4 19 | Example 3: 20 | 21 | Example 3: 22 | 23 | Input: nums = [1] 24 | Output: 1 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= nums.length <= 3 * 104 30 | -3 * 104 <= nums[i] <= 3 * 104 31 | 32 | Each element in the array appears twice except for one element which appears only once. 33 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Diagonal Difference/readme.md: -------------------------------------------------------------------------------- 1 | Given a square matrix, calculate the absolute difference between the sums of its diagonals. 2 | 3 | For example, the square matrix is shown below: 4 | 5 | 1 2 3 6 | 4 5 6 7 | 9 8 9 8 | The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is . 9 | 10 | Function description 11 | 12 | Complete the function in the editor below. 13 | 14 | diagonalDifference takes the following parameter: 15 | 16 | int arr[n][m]: an array of integers 17 | Return 18 | 19 | int: the absolute diagonal difference 20 | Input Format 21 | 22 | The first line contains a single integer, , the number of rows and columns in the square matrix . 23 | Each of the next lines describes a row, , and consists of space-separated integers . 24 | 25 | Constraints 26 | 27 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Staircase/readme.md: -------------------------------------------------------------------------------- 1 | Staircase detail 2 | 3 | This is a staircase of size : 4 | 5 | # 6 | ## 7 | ### 8 | #### 9 | Its base and height are both equal to . It is drawn using # symbols and spaces. The last line is not preceded by any spaces. 10 | 11 | Write a program that prints a staircase of size . 12 | 13 | Function Description 14 | 15 | Complete the staircase function in the editor below. 16 | 17 | staircase has the following parameter(s): 18 | 19 | int n: an integer 20 | Print 21 | 22 | Print a staircase as described above. 23 | 24 | Input Format 25 | 26 | A single integer, , denoting the size of the staircase. 27 | 28 | Constraints 29 | 30 | . 31 | 32 | Output Format 33 | 34 | Print a staircase of size using # symbols and spaces. 35 | 36 | Note: The last line must have spaces in it. -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Intersection of Two Arrays II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector intersect(vector &nums1, vector &nums2) 5 | { 6 | 7 | vector store; 8 | unordered_map check; 9 | for (auto i : nums1) 10 | { 11 | check[i]++; 12 | // increment if already element present else add a new element and increment 13 | } 14 | for (auto i : nums2) 15 | { 16 | if (check[i] > 0) // checking the value(min 1 means present) 17 | { 18 | store.push_back(i); 19 | check[i]--; // decreasing by 1 as there will me multiple element as eg 2 2 20 | } 21 | } 22 | 23 | return store; 24 | } 25 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/coin change/coinChange.java: -------------------------------------------------------------------------------- 1 | long long int count( int S[], int sum, int size ) 2 | { 3 | long long int dp[sum+1][size+1]; 4 | for(int i=0;i<=sum;i++) 5 | { 6 | dp[i][0] = 1; 7 | } 8 | for(int j=1;j<=size;j++) 9 | { 10 | dp[0][j] = 0; 11 | } 12 | for(int i=1;i<=sum;i++) 13 | { 14 | for(int j=1;j<=size;j++) 15 | { 16 | if(S[i-1]<=j) 17 | { 18 | dp[i][j] = dp[i-1][j] + dp[i][j-S[i-1]]; 19 | } 20 | else 21 | { 22 | dp[i][j] = dp[i-1][j]; 23 | } 24 | } 25 | } 26 | return dp[sum][size]; 27 | 28 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Number line Jumps/readme.md: -------------------------------------------------------------------------------- 1 | You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). 2 | 3 | The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. 4 | The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. 5 | You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO. 6 | 7 | Complete the function kangaroo in the editor below. 8 | 9 | kangaroo has the following parameter(s): 10 | 11 | int x1, int v1: starting position and jump distance for kangaroo 1 12 | int x2, int v2: starting position and jump distance for kangaroo 2 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 5- Two Pointers/876. Middle of the Linked List/readme.md: -------------------------------------------------------------------------------- 1 | ## Middle of the Linked List 2 | ### Problem Statement 3 | Given the head of a singly linked list, return the middle node of the linked list. 4 | 5 | If there are two middle nodes, return the second middle node. 6 | 7 | 8 | 9 | 10 | Example 1: 11 | ``` 12 | Input: head = [1,2,3,4,5] 13 | Output: [3,4,5] 14 | Explanation: The middle node of the list is node 3. 15 | 16 | ``` 17 | 18 | Example 2: 19 | ``` 20 | Input: head = [1,2,3,4,5,6] 21 | Output: [4,5,6] 22 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 23 | ``` 24 | 25 | Constraints: 26 | ``` 27 | The number of nodes in the list is in the range [1, 100]. 28 | 1 <= Node.val <= 100 29 | ``` 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary Search Trees/BST To Sorted List/README.md: -------------------------------------------------------------------------------- 1 | ## Flatten BST to Sorted List 2 | 3 | Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST. 4 | 5 | Example 1: 6 | 7 | Input: 8 | 5 9 | / \ 10 | 3 7 11 | / \ / \ 12 | 2 4 6 8 13 | Output: 2 3 4 5 6 7 8 14 | 15 | Example 2: 16 | 17 | Input: 18 | 1 19 | \ 20 | 2 21 | \ 22 | 3 23 | \ 24 | 4 25 | \ 26 | 5 27 | Output: 1 2 3 4 5 28 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Cyclically rotate an array by one/solution.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | void rotate(int arr[], int n); 7 | 8 | int main() 9 | { 10 | int t; 11 | scanf("%d",&t); 12 | while(t--) 13 | { 14 | int n; 15 | scanf("%d",&n); 16 | int a[n] , i; 17 | for(i=0;i> 5 | #define ff first 6 | #define ss second 7 | 8 | int kthSmallest(int mat[MAX][MAX], int n, int k) 9 | { 10 | //Your code here 11 | priority_queue, greater> pq; 12 | for(int i=0; i None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | temp = nums1[:] 7 | i,j,k = 0,0,0 8 | 9 | while i 2 | #include 3 | using namespace std; 4 | 5 | 6 | int getWater(int arr[], int n) 7 | { 8 | int res = 0; 9 | 10 | for(int i = 1; i < n - 1; i++) 11 | { 12 | int res = 0; 13 | 14 | int lMax[n]; 15 | int rMax[n]; 16 | 17 | lMax[0] = arr[0]; 18 | for(int i = 1; i < n; i++) 19 | lMax[i] = max(arr[i], lMax[i - 1]); 20 | 21 | 22 | rMax[n - 1] = arr[n - 1]; 23 | for(int i = n - 2; i >= 0; i--) 24 | rMax[i] = max(arr[i], rMax[i + 1]); 25 | 26 | for(int i = 1; i < n - 1; i++) 27 | res = res + (min(lMax[i], rMax[i]) - arr[i]); 28 | 29 | return res; 30 | } 31 | 32 | return res; 33 | } 34 | 35 | 36 | int main() { 37 | 38 | int arr[] = {5, 0, 6, 2, 3}, n = 5; 39 | 40 | cout< 2 | using namespace std; 3 | 4 | int findMinDiff(int arr[], int n, int m) 5 | { 6 | if (m == 0 || n == 0) 7 | return 0; 8 | 9 | sort(arr, arr + n); 10 | 11 | if (n < m) 12 | return -1; 13 | 14 | int min_diff = INT_MAX; 15 | 16 | for (int i = 0; i + m - 1 < n; i++) { 17 | int diff = arr[i + m - 1] - arr[i]; 18 | if (diff < min_diff) 19 | min_diff = diff; 20 | } 21 | return min_diff; 22 | } 23 | 24 | int main() 25 | { 26 | int arr[] = { 12, 4, 7, 9, 2, 23, 25, 41, 30, 27 | 40, 28, 42, 30, 44, 48, 43, 50 }; 28 | int m = 7; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | cout << "Minimum difference is " 31 | << findMinDiff(arr, n, m); 32 | return 0; 33 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Smallest subarray with sum greater than x/readme.md: -------------------------------------------------------------------------------- 1 | ## Smallest subarray with sum greater than x 2 | 3 | Given an array of integers (A[]) and a number x, find the smallest subarray with sum greater than the given value. 4 | 5 | Note: The answer always exists. It is guaranteed that x doesn't exceed the summation of a[i] (from 1 to N). 6 | 7 | 8 | 9 | Example 1: 10 | ```C 11 | Input: 12 | A[] = {1, 4, 45, 6, 0, 19} 13 | x = 51 14 | Output: 3 15 | Explanation: 16 | Minimum length subarray is 17 | {4, 45, 6} 18 | ``` 19 | Example 2: 20 | ```C 21 | Input: 22 | A[] = {1, 10, 5, 2, 7} 23 | x = 9 24 | Output: 1 25 | Explanation: 26 | Minimum length subarray is {10} 27 | ``` 28 | Expected Time Complexity: O(N) 29 | Expected Auxiliary Space: O(1) 30 | 31 | Constraints: 32 | 1 ≤ N, x ≤ 105 33 | 1 ≤ A[] ≤ 104 34 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Breaking The Records/readme.md: -------------------------------------------------------------------------------- 1 | Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there. 2 | Given the scores for a season, determine the number of times Maria breaks her records for most and least points scored during the season. 3 | 4 | Function Description 5 | 6 | Complete the breakingRecords function in the editor below. 7 | 8 | breakingRecords has the following parameter(s): 9 | 10 | int scores[n]: points scored per game 11 | Returns 12 | 13 | int[2]: An array with the numbers of times she broke her records. Index is for breaking most points records, and index is for breaking least points records. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/MergeKSortedLL/MergeKSortedLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* head; 7 | Node* next; 8 | }; 9 | 10 | Node* MergeK(Node* arr[],int k){ 11 | int i=0; 12 | int last=k-1; 13 | int j; 14 | while(last!=0){ 15 | i=0; 16 | j=last; 17 | while(i=j){ 22 | last=j; 23 | } 24 | } 25 | } 26 | return arr[0]; 27 | } 28 | 29 | Node* createNode(int data){ 30 | Node* head = new Node(data); 31 | } 32 | 33 | Node* flatten(Node* root){ 34 | if(root==NULL || root->next==NULL) 35 | return root; 36 | return merge(root,flatten(root->next)); 37 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary Search Trees/Find a value in BST/readme.md: -------------------------------------------------------------------------------- 1 | Given a BST and a key K. If K is not present in the BST, Insert a new Node with a value equal to K into the BST. 2 | Note: If K is already present in the BST, don't modify the BST. 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | 2 9 | / \ 10 | 1 3 11 | K = 4 12 | Output: 1 2 3 4 13 | Explanation: After inserting the node 4 14 | 15 | 16 | Example 2: 17 | 18 | Input: 19 | 2 20 | / \ 21 | 1 3 22 | \ 23 | 6 24 | K = 4 25 | Output: 1 2 3 4 6 26 | Explanation: After inserting the node 4 27 | 28 | will be 1 2 3 4 6. 29 | 30 | Your Task: 31 | You don't need to read input or print anything. Your task is to complete the function insert() which takes the root of the BST and Key K as input parameters and returns the root of the modified BST after inserting K. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Greedy/Find maximum/readme.md: -------------------------------------------------------------------------------- 1 | Given three stacks of the positive numbers, the task is to find the possible equal maximum sum of the stacks with the removal of top elements allowed. Stacks are represented as an array, and the first index of the array represent the top element of the stack. 2 | The idea is to compare the sum of each stack, if they are not same, remove the top element of the stack having the maximum sum. 3 | Algorithm for solving this problem: 4 | 5 | Find the sum of all elements of in individual stacks. 6 | If the sum of all three stacks is the same, then this is the maximum sum. 7 | Else remove the top element of the stack having the maximum sum among three of stacks. Repeat step 1 and step 2. 8 | The approach works because elements are positive. To make sum equal, we must remove some element from stack having more sum, and we can only remove from the top. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Reverse Level Order Traversal/readme.md: -------------------------------------------------------------------------------- 1 | Given a binary tree of size N, find its reverse level order traversal. i.e.- the traversal must begin from the last level. 2 | 3 | Example 1: 4 | 5 | Input : 6 | 1 7 | / \ 8 | 3 2 9 | 10 | Output: 3 2 1 11 | Explanation: 12 | Traversing level 1 : 3 2 13 | Traversing level 0 : 1 14 | Example 2: 15 | 16 | Input : 17 | 10 18 | / \ 19 | 20 30 20 | / \ 21 | 40 60 22 | 23 | Output: 40 60 20 30 10 24 | Explanation: 25 | Traversing level 2 : 40 60 26 | Traversing level 1 : 20 30 27 | Traversing level 0 : 10 28 | 29 | Your Task: 30 | You don't need to read input or print anything. Complete the function reverseLevelOrder() which takes the root of the tree as input parameter and returns a list containing the reverse level order traversal of the given tree. 31 | 32 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/SplitList/SplitList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* head; 7 | Node* next; 8 | }; 9 | 10 | Node* Split(Node* head,Node **head1_ref,Node **head2_ref){ 11 | Node* slow=head; 12 | Node* fast= head; 13 | while(fast!=head && fast->next!=head){ 14 | slow=slow->next; 15 | fast=fast->next->next; 16 | } 17 | *head1_ref = head; 18 | *head2_ref= slow->next; 19 | slow->next= *head1_ref; 20 | Node* curr= *head2_ref; 21 | while(curr->next!=head){ 22 | curr=curr->next; 23 | } 24 | curr->next=*head2_ref; 25 | } 26 | 27 | Node* createNode(int data){ 28 | Node* head = new Node(data); 29 | } 30 | 31 | int main(){ 32 | createNode(1); 33 | createNode(3); 34 | Split(head,*head1_ref,*head2_ref); 35 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Greedy/Job Sequencing Problem/readme.md: -------------------------------------------------------------------------------- 1 | Given a set of N jobs where each jobi has a deadline and profit associated with it. Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit if and only if the job is completed by its deadline. The task is to find the number of jobs done and the maximum profit. 2 | 3 | Note: Jobs will be given in the form (Jobid, Deadline, Profit) associated with that Job. 4 | 5 | 6 | Example 1: 7 | 8 | Input: 9 | N = 4 10 | Jobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)} 11 | Output: 12 | 2 60 13 | Explanation: 14 | Job1 and Job3 can be done with 15 | maximum profit of 60 (20+40). 16 | Example 2: 17 | 18 | Input: 19 | N = 5 20 | Jobs = {(1,2,100),(2,1,19),(3,2,27), 21 | (4,1,25),(5,1,15)} 22 | Output: 23 | 2 127 24 | Explanation: 25 | 2 jobs can be done with 26 | maximum profit of 127 (100+27). -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Maximum Subarray/readme.md: -------------------------------------------------------------------------------- 1 | ## Maximum Subarray 2 | 3 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 4 | 5 | A subarray is a contiguous part of an array. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 12 | Output: 6 13 | Explanation: [4,-1,2,1] has the largest sum = 6. 14 | 15 | Example 2: 16 | 17 | Input: nums = [1] 18 | Output: 1 19 | 20 | Example 3: 21 | 22 | Input: nums = [5,4,-1,7,8] 23 | Output: 23 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 105 29 | -104 <= nums[i] <= 104 30 | 31 | 32 | 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. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/BFS of a Graph/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to return Breadth First Traversal of given graph. 4 | public ArrayList bfsOfGraph(int V,ArrayList> adj) 5 | { 6 | ArrayList bfs= new ArrayList<>(); 7 | Queue queue= new LinkedList<>(); 8 | ArrayList visited= new ArrayList<>(); 9 | 10 | queue.add(0); 11 | 12 | while(!(queue.isEmpty())) { 13 | int p= queue.poll(); 14 | if(!(visited.contains(p))) { 15 | bfs.add(p); 16 | for(int i=0; i 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* left; 7 | Node* right; 8 | 9 | Node(int x){ 10 | data=x; 11 | left=right=NULL; 12 | } 13 | }; 14 | 15 | void TopView(Node *root){ 16 | 17 | map m; 18 | queue> q; 19 | if(!root){ 20 | return ans; 21 | } 22 | q.push(root); 23 | while(!q.empty()){ 24 | Node* t= q.front().first; 25 | int h= q.front().second; 26 | q.pop(); 27 | if(!m[h]){ 28 | m[h]=t->data; 29 | } 30 | if(t->left){ 31 | q.push({t->left,h-1}); 32 | } 33 | if(t->right){ 34 | q.push({t->right,h+1}); 35 | } 36 | } 37 | for(auto x:m){ 38 | cout< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* head; 7 | Node* next; 8 | Node* prev; 9 | }; 10 | 11 | Node* Rotate(Node* head,int N){ 12 | if(N==0){ 13 | return head; 14 | } 15 | int count; 16 | Node* current = head; 17 | while(countnext; 19 | count++; 20 | } 21 | Node* NthNode = =current; 22 | 23 | while(current->next!=NULL){ 24 | current=current->next; 25 | current->next=head; 26 | head->prev=current; 27 | head=NthNode->next; 28 | head->prev=NULL; 29 | } 30 | } 31 | 32 | Node* createNode(int data){ 33 | Node* head = new Node(data); 34 | } 35 | 36 | int main(){ 37 | createNode(1); 38 | createNode(3); 39 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/704. Binary Search/readme.md: -------------------------------------------------------------------------------- 1 | ## Binary search 2 | ### Problem Statement 3 | 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. 4 | 5 | You must write an algorithm with O(log n) runtime complexity. 6 | 7 | 8 | Example 1: 9 | ``` 10 | Input: nums = [-1,0,3,5,9,12], target = 9 11 | Output: 4 12 | Explanation: 9 exists in nums and its index is 4 13 | ``` 14 | 15 | Example 2: 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 | Constraints: 23 | ``` 24 | 1 <= nums.length <= 104 25 | -104 < nums[i], target < 104 26 | All the integers in nums are unique. 27 | nums is sorted in ascending order. 28 | ``` 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 2 - Two Pointers/189. Rotate Array/readme.md: -------------------------------------------------------------------------------- 1 | ## Rotate Array 2 | ### Problem Statement 3 | Given an array, rotate the array to the right by k steps, where k is non-negative. 4 | 5 | 6 | 7 | 8 | Example 1: 9 | ``` 10 | Input: nums = [1,2,3,4,5,6,7], k = 3 11 | Output: [5,6,7,1,2,3,4] 12 | Explanation: 13 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 14 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 15 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 16 | ``` 17 | 18 | Example 2: 19 | ``` 20 | Input: nums = [-1,-100,3,99], k = 2 21 | Output: [3,99,-1,-100] 22 | Explanation: 23 | rotate 1 steps to the right: [99,-1,-100,3] 24 | rotate 2 steps to the right: [3,99,-1,-100] 25 | ``` 26 | 27 | Constraints: 28 | ``` 29 | 1 <= nums.length <= 105 30 | -231 <= nums[i] <= 231 - 1 31 | 0 <= k <= 105 32 | ``` 33 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Strings/Sentence to Mobile Keypad Equivalent/KeypadEqv.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | string position[] = {"2","22","222","3","33","333","4","44","444","5","55","555", 7 | "6","66","666","7","77","777","7777","8","88","888", 8 | "9","99","999","9999"}; 9 | 10 | string initial_str = "Welcome to Hacktoberfest", final_str = ""; 11 | 12 | //Transforms the entire string to uppercase 13 | transform(initial_str.begin(), initial_str.end(), initial_str.begin(), ::toupper); 14 | for (int i = 0; i < initial_str.length(); i++) { 15 | if (initial_str[i] == ' ') 16 | final_str += "0"; 17 | else 18 | final_str += position[int(initial_str[i]-'A')]; 19 | } 20 | 21 | cout<<"The mobile keypad equivalent of the given string is: "< 2 | 3 | using namespace std; 4 | 5 | 6 | bool findPair(int arr[], int size, int n); 7 | 8 | int main() 9 | { 10 | int t; 11 | cin>>t; 12 | while(t--) 13 | { 14 | int l,n; 15 | cin>>l>>n; 16 | int arr[l]; 17 | for(int i=0;i>arr[i]; 19 | if(findPair(arr, l, n)) 20 | cout<<1<=0;i--) 34 | { 35 | int x = arr[i] - n; 36 | flag = binary_search(arr,arr+size,x); 37 | if(flag == true) 38 | return flag; 39 | } 40 | return flag; 41 | 42 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Searching/recursiveLinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int linearSearch(int arr[], int, int, int); 4 | int linearSearch(int arr[],int l,int r,int x) { 5 | if (r>n; 19 | int arr[n]; 20 | for(int i=0;i>arr[i]; 22 | } 23 | cout<<"Enter Element to be searched for: "; 24 | cin>>numToSearch; 25 | int index=linearSearch(arr,0,n-1,numToSearch); 26 | if(index!=-1){ 27 | cout< List[int]: 3 | temp,ans = [],[] 4 | n = len(nums) 5 | i = j = 0 6 | 7 | while i2->4->5 10 | Output: 2 4 5 11 | Explanation: In the given linked list 12 | 2 ->2 -> 4-> 5, only 2 occurs more 13 | than 1 time. 14 | ``` 15 | 16 | Example 2: 17 | ```C 18 | Input: 19 | LinkedList: 2->2->2->2->2 20 | Output: 2 21 | Explanation: In the given linked list 22 | 2 ->2 ->2 ->2 ->2, 2 is the only element 23 | and is repeated 5 times. 24 | ``` 25 | Expected Time Complexity : O(N) 26 | Expected Auxilliary Space : O(1) 27 | 28 | Constraints: 29 | 1 <= Number of nodes <= 10^4 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/FlattenLL/Flatten.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* head; 7 | Node* next; 8 | }; 9 | 10 | Node* merge(Node* a,Node* b){ 11 | if(a==NULL) return b; 12 | if(b==NULL) return a; 13 | 14 | Node* result; 15 | if(a->datadata){ 16 | result=a; 17 | result->bottom=merge(a->bottom,b); 18 | } 19 | else{ 20 | result=b; 21 | result->bottom=merge(a,b->bottom); 22 | } 23 | 24 | result->next=NULL; 25 | return result; 26 | } 27 | 28 | Node* createNode(int data){ 29 | Node* head = new Node(data); 30 | } 31 | 32 | Node* flatten(Node* root){ 33 | if(root==NULL || root->next==NULL) 34 | return root; 35 | return merge(root,flatten(root->next)); 36 | } 37 | 38 | int main(){ 39 | createNode(1); 40 | createNode(3); 41 | flatten(root); 42 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Median of 2 Sorted Arrays of Different Sizes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static double medianOfArrays(int n, int m, int a[], int b[]) 4 | { 5 | //Creating ArrayList 6 | ArrayList merged= new ArrayList<>(); 7 | 8 | 9 | //Adding numbers to ArrayList 10 | for(int i=0; i 2 | #include 3 | #define ll long long 4 | 5 | using namespace std; 6 | 7 | void solve(int t){ 8 | while (t--){ 9 | int n,k; 10 | cin >> n >> k ; 11 | vector v; 12 | int x,bc=0; 13 | for(int i=0;i> x; 15 | v.push_back(x); 16 | if(!(i==0)){ 17 | if((k-(v[i]+v[i-1]))>0){ 18 | bc+=(k-(v[i]+v[i-1])); 19 | v[i]+=(k-(v[i]+v[i-1])); 20 | } 21 | } 22 | } 23 | cout << bc << "\n"; 24 | for(int i=0;i> t; 36 | solve(t); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Median of 2 Sorted Arrays of Different Sizes/Readme.md: -------------------------------------------------------------------------------- 1 | ## Median of 2 Sorted Arrays of Different Sizes 2 | ### Problem statement 3 | The task is to complete the function MedianOfArrays() that takes array1 and array2 as input and returns their median. 4 | 5 | Example 1: 6 | 7 | Input: 8 | m = 3, n = 4 9 | array1[] = {1,5,9} 10 | array2[] = {2,3,6,7} 11 | Output: 5 12 | Explanation: The middle element for 13 | {1,2,3,5,6,7,9} is 5 14 | 15 | Example 2: 16 | 17 | Input: 18 | m = 2, n = 4 19 | array1[] = {4,6} 20 | array2[] = {1,2,3,5} 21 | Output: 3.5 22 | 23 | **Link** : https://practice.geeksforgeeks.org/problems/median-of-2-sorted-arrays-of-different-sizes/1 24 | 25 | Expected Time Complexity: O(min(log n, log m)) 26 | Expected Auxiliary Space: O((n+m)/2) 27 | 28 | **Constraints**: 29 | 0 ≤ m,n ≤ 104 30 | 1 ≤ array1[i], array2[i] ≤ 105 31 | 32 | Tag : **Medium** 33 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Clone linked list(random pointer)/solution.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | int data; 4 | Node next, arb; 5 | Node(int d) 6 | { 7 | data = d; 8 | next = arb = null; 9 | } 10 | }*/ 11 | 12 | class Clone { 13 | //Function to clone a linked list with next and random pointer. 14 | Node copyList(Node head) { 15 | if(head==null) 16 | return null; 17 | HashMap nodeMap=new HashMap<>(); 18 | Node temp=head; 19 | while(temp!=null){ 20 | Node x=new Node(temp.data); 21 | nodeMap.put(temp,x); 22 | temp=temp.next; 23 | } 24 | temp=head; 25 | while(temp!=null){ 26 | nodeMap.get(temp).next=nodeMap.get(temp.next); 27 | nodeMap.get(temp).arb=nodeMap.get(temp.arb); 28 | temp=temp.next; 29 | } 30 | return nodeMap.get(head); 31 | } 32 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/T-primes/T-primes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int prime(int a){ 7 | int c=0; 8 | for(int i=2;i<=sqrt(a);i++){ 9 | if(a%i==0){ 10 | c++; 11 | } 12 | if(c>0){ 13 | return 0; 14 | } 15 | } 16 | return 1; 17 | } 18 | 19 | 20 | 21 | int main(){ 22 | ios::sync_with_stdio(0); 23 | cin.tie(0); 24 | long long n,y; 25 | double x; 26 | cin >> n; 27 | long long arr[n],count=0; 28 | for(int i=0;i>arr[i]; 30 | } 31 | for(int i=0;i 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* head; 7 | Node* next; 8 | }; 9 | 10 | bool Palindrome(Node* head){ 11 | Node* slow=head; 12 | Node* fast=head; 13 | while(fast!=NULL && fast->next!=NULL){ 14 | slow=slow->next; 15 | fast=fast->next->next; 16 | } 17 | } 18 | 19 | Node* prev =NULL; 20 | Node* next; 21 | Node* curr=slow; 22 | 23 | while(curr!=NULL){ 24 | next=curr->next; 25 | curr->next=prev; 26 | prev=curr; 27 | curr=next; 28 | } 29 | 30 | fast=head; 31 | while(prev!=NULL){ 32 | if(fast->data!=prev->data){ 33 | return false; 34 | } 35 | fast=fast->next; 36 | prev=prev->next; 37 | } 38 | 39 | Node* createNode(int data){ 40 | Node* head = new Node(data); 41 | } 42 | 43 | int main(){ 44 | createNode(1); 45 | createNode(3); 46 | Palindrome(head); 47 | } -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 6- Sliding Window/3. Longest Substring Without Repeating Characters/readme.md: -------------------------------------------------------------------------------- 1 | ## Longest Substring Without Repeating Characters 2 | ### Problem Statement 3 | Given a string s, find the length of the longest substring without repeating characters. 4 | 5 | 6 | 7 | 8 | Example 1: 9 | ``` 10 | Input: s = "abcabcbb" 11 | Output: 3 12 | Explanation: The answer is "abc", with the length of 3. 13 | 14 | ``` 15 | 16 | Example 2: 17 | ``` 18 | Input: s = "bbbbb" 19 | Output: 1 20 | Explanation: The answer is "b", with the length of 1. 21 | ``` 22 | 23 | Example 3: 24 | ``` 25 | Input: s = "pwwkew" 26 | Output: 3 27 | Explanation: The answer is "wke", with the length of 3. 28 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 29 | ``` 30 | 31 | Constraints: 32 | ``` 33 | 0 <= s.length <= 5 * 104 34 | s consists of English letters, digits, symbols and spaces. 35 | ``` 36 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Searching/interpolationSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int interpolationSearch(int arr[], int n, int x) 5 | { 6 | int lo = 0, hi = (n - 1); 7 | 8 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 9 | { 10 | if (lo == hi) 11 | { 12 | if (arr[lo] == x) return lo; 13 | return -1; 14 | } 15 | 16 | int pos = lo + (((double)(hi - lo) / 17 | (arr[hi] - arr[lo])) * (x - arr[lo])); 18 | 19 | 20 | if (arr[pos] == x) 21 | return pos; 22 | 23 | if (arr[pos] < x) 24 | lo = pos + 1; 25 | 26 | else 27 | hi = pos - 1; 28 | } 29 | return -1; 30 | } 31 | 32 | int main() 33 | { 34 | int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 35 | 22, 23, 24, 33, 35, 42, 47}; 36 | int n = sizeof(arr)/sizeof(arr[0]); 37 | 38 | int x = 18; 39 | int index = interpolationSearch(arr, n, x); 40 | if (index != -1) 41 | cout << "Element found at index " << index; 42 | else 43 | cout << "Element not found."; 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.minimap.enabled": false, 3 | "editor.wrappingIndent": "indent", 4 | "editor.overviewRulerBorder": false, 5 | "editor.lineHeight": 24, 6 | "[markdown]": { 7 | "editor.quickSuggestions": true 8 | }, 9 | "files.defaultLanguage": "markdown", 10 | "files.exclude": { 11 | "**/node_modules": true 12 | }, 13 | "files.watcherExclude": { 14 | "**/node_modules": true 15 | }, 16 | "foam.edit.linkReferenceDefinitions": "off", 17 | "foam.openDailyNote.directory": "journal", 18 | "foam.openDailyNote.titleFormat": "fullDate", 19 | "git.enableSmartCommit": true, 20 | "git.postCommitCommand": "sync", 21 | "markdown.preview.breaks": true, 22 | "pasteImage.path": "${projectRoot}/attachments", 23 | "pasteImage.showFilePathConfirmInputBox": true, 24 | "prettier.singleQuote": false, 25 | "spellright.notificationClass": "warning", 26 | "vscodeMarkdownNotes.noteCompletionConvention": "noExtension", 27 | "vscodeMarkdownNotes.slugifyMethod": "github-slugger", 28 | } 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/Rat in maze problem/readme.md: -------------------------------------------------------------------------------- 1 | Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it. 2 | Note: In a path, no cell can be visited more than one time. 3 | 4 | Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order. 5 | Note: In case of no path, return an empty list. The driver will output "-1" automatically. 6 | 7 | Expected Time Complexity: O((N2)4). 8 | Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths. 9 | 10 | Constraints: 11 | 2 ≤ N ≤ 5 12 | 0 ≤ m[i][j] ≤ 1 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 1 - Binary Search/35. Search Insert Position/readme.md: -------------------------------------------------------------------------------- 1 | ## Search Insert Position 2 | ### Problem Statement 3 | 4 | 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. 5 | 6 | You must write an algorithm with O(log n) runtime complexity. 7 | 8 | 9 | Example 1: 10 | ``` 11 | Input: nums = [1,3,5,6], target = 5 12 | Output: 2 13 | ``` 14 | Example 2: 15 | ``` 16 | Input: nums = [1,3,5,6], target = 2 17 | Output: 1 18 | ``` 19 | Example 3: 20 | ``` 21 | Input: nums = [1,3,5,6], target = 7 22 | Output: 4 23 | ``` 24 | Example 4: 25 | ``` 26 | Input: nums = [1,3,5,6], target = 0 27 | Output: 0 28 | ``` 29 | Example 5: 30 | ``` 31 | Input: nums = [1], target = 0 32 | Output: 0 33 | ``` 34 | Constraints: 35 | ``` 36 | 1 <= nums.length <= 104 37 | -104 <= nums[i] <= 104 38 | nums contains distinct values sorted in ascending order. 39 | -104 <= target <= 104 40 | ``` 41 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Two Sum/readme.md: -------------------------------------------------------------------------------- 1 | ## Two Sum 2 | 3 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 4 | 5 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | You can return the answer in any order. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [2,7,11,15], target = 9 14 | Output: [0,1] 15 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 16 | 17 | Example 2: 18 | 19 | Input: nums = [3,2,4], target = 6 20 | Output: [1,2] 21 | 22 | Example 3: 23 | 24 | Input: nums = [3,3], target = 6 25 | Output: [0,1] 26 | 27 | 28 | Constraints: 29 | 30 | 2 <= nums.length <= 104 31 | -109 <= nums[i] <= 109 32 | -109 <= target <= 109 33 | Only one valid answer exists. 34 | 35 | 36 | Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Dynamic Programming/0-1 knapsack/readme.md: -------------------------------------------------------------------------------- 1 | You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item. 2 | In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property). 3 | Your Task: 4 | Complete the function knapSack() which takes maximum capacity W, weight array wt[], value array val[], and the number of items n as a parameter and returns the maximum possible value you can get. 5 | 6 | Expected Time Complexity: O(N*W). 7 | Expected Auxiliary Space: O(N*W) 8 | 9 | Constraints: 10 | 1 ≤ N ≤ 1000 11 | 1 ≤ W ≤ 1000 12 | 1 ≤ wt[i] ≤ 1000 13 | 1 ≤ v[i] ≤ 1000 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Greedy/Huffman Coding/readme.md: -------------------------------------------------------------------------------- 1 | Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree. 2 | Note: If two elements have same frequency, then the element which occur at first will be taken on the left of Binary Tree and other one to the right. 3 | 4 | Example 1: 5 | 6 | S = "abcdef" 7 | f[] = {5, 9, 12, 13, 16, 45} 8 | Output: 9 | 0 100 101 1100 1101 111 10 | Explanation: 11 | HuffmanCodes will be: 12 | f : 0 13 | c : 100 14 | d : 101 15 | a : 1100 16 | b : 1101 17 | e : 111 18 | Hence printing them in the PreOrder of Binary 19 | Tree. 20 | Your Task: 21 | You don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Union of two arrays/readme.md: -------------------------------------------------------------------------------- 1 | ## Union of two arrays 2 | 3 | Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays. 4 | 5 | Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union. 6 | 7 | 8 | Example 1: 9 | ```C 10 | Input: 11 | 5 3 12 | 1 2 3 4 5 13 | 1 2 3 14 | Output: 15 | 5 16 | Explanation: 17 | 1, 2, 3, 4 and 5 are the 18 | elements which comes in the union set 19 | of both arrays. So count is 5. 20 | ``` 21 | 22 | Example 2: 23 | ```C 24 | Input: 25 | 6 2 26 | 85 25 1 32 54 6 27 | 85 2 28 | Output: 29 | 7 30 | Explanation: 31 | 85, 25, 1, 32, 54, 6, and 32 | 2 are the elements which comes in the 33 | union set of both arrays. So count is 7. 34 | ``` 35 | 36 | Expected Time Complexity : O((n+m)log(n+m)) 37 | Expected Auxilliary Space : O(n+m) 38 | 39 | Constraints: 40 | 1 ≤ n, m ≤ 10^5 41 | 0 ≤ a[i], b[i] < 10^5 42 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Sort an array of 0s, 1s and 2s/Readme.md: -------------------------------------------------------------------------------- 1 | ## Sort an array of 0s, 1s and 2s 2 | ### Problem Statement 3 | 4 | Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. 5 | 6 | Example 1: 7 | 8 | Input: 9 | N = 5 10 | arr[]= {0 2 1 2 0} 11 | Output: 12 | 0 0 1 2 2 13 | Explanation: 14 | 0s 1s and 2s are segregated 15 | into ascending order. 16 | 17 | Example 2: 18 | 19 | Input: 20 | N = 3 21 | arr[] = {0 1 0} 22 | Output: 23 | 0 0 1 24 | Explanation: 25 | 0s 1s and 2s are segregated 26 | into ascending order. 27 | 28 | Your Task: 29 | You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. 30 | 31 | 32 | Expected Time Complexity: O(N) 33 | 34 | Expected Auxiliary Space: O(1) 35 | 36 | 37 | **Constraints:** 38 | 39 | 1 <= N <= 10^6 40 | 41 | 0 <= A[i] <= 2 42 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/Subarray with 0 sum/Readme.md: -------------------------------------------------------------------------------- 1 | ## Subarray with 0 sum 2 | # Problem Statement 3 | Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum. 4 | 5 | Example 1: 6 | 7 | Input: 8 | 5 9 | 4 2 -3 1 6 10 | 11 | Output: 12 | Yes 13 | 14 | Explanation: 15 | 2, -3, 1 is the subarray 16 | with sum 0. 17 | 18 | Example 2: 19 | 20 | Input: 21 | 5 22 | 4 2 0 1 6 23 | 24 | Output: 25 | Yes 26 | 27 | Explanation: 28 | 0 is one of the element in the array so there exist a subarray with sum 0. 29 | 30 | Your Task: 31 | You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code. 32 | 33 | Expected Time Complexity: O(n). 34 | 35 | Expected Auxiliary Space: O(n). 36 | 37 | **Constraints:** 38 | 39 | 1 <= n <= 104 40 | 41 | -105 <= a[i] <= 105 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Stacks & Queues/Reverse First K elements of Queue/readme.md: -------------------------------------------------------------------------------- 1 | ## Problem statement 2 | Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order. 3 | 4 | Only following standard operations are allowed on queue. 5 | 6 | * enqueue(x) : Add an item x to rear of queue 7 | * dequeue() : Remove an item from front of queue 8 | * size() : Returns number of elements in queue. 9 | * front() : Finds front item. 10 | 11 | ## Example 12 | ``` 13 | Input: 14 | 5 3 15 | 1 2 3 4 5 16 | 17 | Output: 18 | 3 2 1 4 5 19 | 20 | Explanation: After reversing the given input from the 3rd position the resultant output 21 | will be 3 2 1 4 5. 22 | ``` 23 | ``` 24 | Input: 25 | 4 4 26 | 4 3 2 1 27 | 28 | Output: 29 | 1 2 3 4 30 | 31 | Explanation: After reversing the given input from the 4th position the resultant output will be 1 2 3 4. 32 | ``` 33 | 34 | ## Constraints 35 | 1 <= N <= 1000 36 | 37 | 1 <= K <= N 38 | 39 | -------------------------------------------------------------------------------- /.foam/templates/your-first-template.md: -------------------------------------------------------------------------------- 1 | # Foam Note Templates 2 | 3 | Foam includes note templates! 4 | This allows you to easily create notes that have similar structure without having to use copy/paste :) 5 | 6 | Templates support the [VS Code's Snippet Syntax](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax), which means you can: 7 | - add variables to the newly created note 8 | - add tabstop to automatically navigate to the key parts of the note, just like a form 9 | Below you can see an example showing a todo list and a timestamp. 10 | 11 | ## Todo List 12 | 13 | 1. ${1:First tabstop} 14 | 2. ${2:A second tabstop} 15 | 3. ${3:A third tabstop} 16 | 17 | Note Created: ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE} 18 | 19 | --- 20 | 21 | Try out the above example by running the `Foam: Create New Note From Template` command and selecting the `your-first-template` template. Notice what happens when your new note is created! 22 | 23 | To remove this template, simply delete the `.foam/templates/your-first-template.md` file. 24 | 25 | Enjoy! 26 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Intersection of 2 LL/readme.md: -------------------------------------------------------------------------------- 1 | Given two lists sorted in increasing order, create a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. 2 | Note: The list elements are not necessarily distinct. 3 | 4 | Example 1: 5 | 6 | Input: 7 | L1 = 1->2->3->4->6 8 | L2 = 2->4->6->8 9 | Output: 2 4 6 10 | Explanation: For the given first two 11 | linked list, 2, 4 and 6 are the elements 12 | in the intersection. 13 | 14 | Example 2: 15 | 16 | Input: 17 | L1 = 10->20->40->50 18 | L2 = 15->40 19 | Output: 40 20 | Your Task: 21 | The task is to complete the function intersection() which should find the intersection of two linked list and add all the elements in intersection to the third linked list and return the head of the third linked list. 22 | 23 | Expected Time Complexity : O(n+m) 24 | Expected Auxilliary Space : O(n+m) 25 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Intersection of Two Arrays II/readme.md: -------------------------------------------------------------------------------- 1 | ## Intersection of Two Arrays II 2 | 3 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 10 | Output: [2,2] 11 | 12 | Example 2: 13 | 14 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 15 | Output: [4,9] 16 | Explanation: [9,4] is also accepted. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= nums1.length, nums2.length <= 1000 22 | 0 <= nums1[i], nums2[i] <= 1000 23 | 24 | 25 | Follow up: 26 | 27 | What if the given array is already sorted? How would you optimize your algorithm? 28 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 29 | What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/T-primes/readme.md: -------------------------------------------------------------------------------- 1 | https://codeforces.com/problemset/problem/230/B 2 | codeforces 1300 rated question 3 | T-primes 4 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, 5 | we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. 6 | 7 | You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. 8 | 9 | Input 10 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. 11 | The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). 12 | 13 | Please, do not use the %lld specifier to read or write 64-bit integers in С++. 14 | It is advised to use the cin, cout streams or the %I64d specifier 15 | 16 | Output 17 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" 18 | (without the quotes), if it isn't. 19 | 20 | Examples 21 | input 22 | 3 23 | 4 5 6 24 | 25 | output 26 | YES 27 | NO 28 | NO 29 | 30 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Zig Zag Traversal/ZigZag.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* left; 7 | Node* right; 8 | 9 | Node(int x){ 10 | data=x; 11 | left=right=NULL; 12 | } 13 | }; 14 | 15 | vector ZigZag(Node *root){ 16 | vector ans; 17 | map m; 18 | queue> q; 19 | if(!root){ 20 | return ans; 21 | } 22 | 23 | q.push(root); 24 | int f=1; 25 | 26 | while(!q.empty()){ 27 | vector temp; 28 | int sz= q.size(); 29 | while(sz--){ 30 | Node* t= q.front(); 31 | temp.push_back(t->data); 32 | q.pop(); 33 | if(t->left){ 34 | q.push(t->left); 35 | } 36 | if(t->right) { 37 | q.push(t->right); 38 | } 39 | } 40 | if(f%2==0){ 41 | reverse(temp.begin(),temp.end()); 42 | } 43 | for(int i=0;i 2-> 3 13 | 2nd list 4->5 14 | 3rd list 5->6 15 | 4th list 7->8 16 | The merged list will be 17 | 1->2->3->4->5->5->6->7->8. 18 | 19 | Example 2: 20 | 21 | Input: 22 | K = 3 23 | value = {{1,3},{4,5,6},{8}} 24 | Output: 1 3 4 5 6 8 25 | Explanation: 26 | The test case has 3 sorted linked 27 | list of size 2, 3, 1. 28 | 1st list 1 -> 3 29 | 2nd list 4 -> 5 -> 6 30 | 3rd list 8 31 | The merged list will be 32 | 1->3->4->5->6->8. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/Making wired Connections/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vectorvis; 4 | vector>graph; 5 | void dfs(int u , int par){ 6 | vis[u]=1; 7 | for(auto v : graph[u]){ 8 | if(v==par)continue; 9 | if(vis[v] != 1)dfs(v,u); 10 | } 11 | } 12 | 13 | int makeConnected(int n, vector>& connections) { 14 | int m = connections.size(); 15 | if(m < n-1)return -1; 16 | vis.resize(n); 17 | graph.resize(n); 18 | for(int i = 0 ; i< m;i++){ 19 | int u = connections[i][0], v = connections[i][1] ; 20 | graph[u].push_back(v); 21 | graph[v].push_back(u); 22 | } 23 | 24 | int dissconnected =0; 25 | for(int i = 0 ; i< n ;i++){ 26 | if(vis[i] !=1){ 27 | dfs(i,-1); 28 | dissconnected++ ; 29 | } 30 | } 31 | dissconnected-- ; 32 | 33 | return dissconnected; 34 | } 35 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Binary Removals/Binary Removals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | T prime(T a){ 8 | int c=0; 9 | for(int i=2;i<=sqrt(a);i++){ 10 | if(a%i==0){ 11 | c++; 12 | } 13 | if(c>0){ 14 | return 0; 15 | } 16 | } 17 | return 1; 18 | } 19 | 20 | int main(){ 21 | ios::sync_with_stdio(0); 22 | cin.tie(0); 23 | 24 | int t; 25 | cin >> t; 26 | while(t--){ 27 | string s; 28 | cin >> s; 29 | int yoyo=0,hoho=0; 30 | for(int i=0;i 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | void segregateElements(int arr[],int n) 9 | { 10 | // Your code goes here 11 | queue q; 12 | for(int i = 0; i=0) 15 | q.push(arr[i]); 16 | } 17 | for(int i = 0; i>t; 35 | while(t--) 36 | { 37 | int n; 38 | cin>>n; 39 | int a[n]; 40 | for(int i=0;i>a[i]; 42 | Solution ob; 43 | ob.segregateElements(a,n); 44 | 45 | for(int i=0;i false 15 | call isBadVersion(5) -> true 16 | call isBadVersion(4) -> true 17 | Then 4 is the first bad version. 18 | ``` 19 | Example 2: 20 | ``` 21 | Input: n = 1, bad = 1 22 | Output: 1 23 | ``` 24 | 25 | Constraints: 26 | ``` 27 | 1 <= bad <= n <= 231 - 1 28 | ``` 29 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Stacks & Queues/Parenthesis Checker/readme.md: -------------------------------------------------------------------------------- 1 | ## Parenthesis Checker 2 | 3 | Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. 4 | For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”. 5 | 6 | 7 | 8 | Example 1: 9 | ```C 10 | Input: 11 | {([])} 12 | Output: 13 | true 14 | Explanation: 15 | { ( [ ] ) }. Same colored brackets can form 16 | balaced pairs, with 0 number of 17 | unbalanced bracket. 18 | ``` 19 | 20 | Example 2: 21 | ```C 22 | Input: 23 | () 24 | Output: 25 | true 26 | Explanation: 27 | (). Same bracket can form balanced pairs, 28 | and here only 1 type of bracket is 29 | present and in balanced way. 30 | ``` 31 | Example 3: 32 | ```C 33 | Input: 34 | ([] 35 | Output: 36 | false 37 | Explanation: 38 | ([]. Here square bracket is balanced but 39 | the small bracket is not balanced and 40 | Hence , the output will be unbalanced. 41 | ``` 42 | 43 | Expected Time Complexity: O(|x|) 44 | Expected Auixilliary Space: O(|x|) 45 | 46 | Constraints: 47 | 1 ≤ |x| ≤ 32000 48 | -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Best Time to Buy and Sell Stock/readme.md: -------------------------------------------------------------------------------- 1 | ## Best Time to Buy and Sell Stock 2 | 3 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 4 | 5 | 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. 6 | 7 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: prices = [7,1,5,3,6,4] 14 | Output: 5 15 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 16 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 17 | Example 2: 18 | 19 | Input: prices = [7,6,4,3,1] 20 | Output: 0 21 | Explanation: In this case, no transactions are done and the max profit = 0. 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= prices.length <= 105 27 | 0 <= prices[i] <= 104 -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Data Structure/Data Structure- 1/Reshape the Matrix/readme.md: -------------------------------------------------------------------------------- 1 | ## Reshape the Matrix 2 | 3 | In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. 4 | 5 | You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. 6 | 7 | The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. 8 | 9 | If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: mat = [[1,2],[3,4]], r = 1, c = 4 16 | Output: [[1,2,3,4]] 17 | 18 | Example 2: 19 | 20 | 21 | Input: mat = [[1,2],[3,4]], r = 2, c = 4 22 | Output: [[1,2],[3,4]] 23 | 24 | 25 | Constraints: 26 | 27 | m == mat.length 28 | n == mat[i].length 29 | 1 <= m, n <= 100 30 | -1000 <= mat[i][j] <= 1000 31 | 1 <= r, c <= 300 -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/plus minus/readme.md: -------------------------------------------------------------------------------- 1 | Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal. 2 | 3 | Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable. 4 | 5 | Example 6 | 7 | There are elements, two positive, two negative and one zero. Their ratios are , and . Results are printed as: 8 | 9 | 0.400000 10 | 0.400000 11 | 0.200000 12 | Function Description 13 | 14 | Complete the plusMinus function in the editor below. 15 | 16 | plusMinus has the following parameter(s): 17 | 18 | int arr[n]: an array of integers 19 | Print 20 | Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with digits after the decimal. The function should not return a value. 21 | 22 | Input Format 23 | 24 | The first line contains an integer, , the size of the array. 25 | The second line contains space-separated integers that describe . 26 | 27 | Constraints -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Smallest subarray with sum greater than x/solution.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | 10 | int smallestSubWithSum(int arr[], int n, int k) 11 | { 12 | 13 | int windowSum = 0; 14 | int len = INT_MAX; 15 | int left = 0; 16 | 17 | for (int right = 0; right < n; right++) 18 | { 19 | windowSum += arr[right]; 20 | while (windowSum > k && left <= right) 21 | { 22 | len = min(len, right - left + 1); 23 | windowSum -= arr[left]; 24 | left++; 25 | } 26 | } 27 | return len; 28 | } 29 | }; 30 | 31 | // { Driver Code Starts. 32 | 33 | int main() { 34 | // your code goes here 35 | int t; 36 | cin>>t; 37 | while(t--) 38 | { 39 | int n,x; 40 | cin>>n>>x; 41 | int a[n]; 42 | for(int i=0;i>a[i]; 44 | Solution obj; 45 | cout< 2 | using namespace std; 3 | 4 | 5 | 6 | void heapify(int arr[], int n, int i) { 7 | int smallest = i; 8 | int l = 2 * i + 1; 9 | int r = 2 * i + 2; 10 | if (l < n && arr[l] < arr[smallest]) 11 | smallest = l; 12 | if (r < n && arr[r] < arr[smallest]) 13 | smallest = r; 14 | if (smallest != i) { 15 | swap(arr[i], arr[smallest]); 16 | heapify(arr, n, smallest); 17 | } 18 | } 19 | 20 | void heapSort(int arr[], int n) { 21 | for (int i = n / 2 - 1; i >= 0; i--) 22 | heapify(arr, n, i); 23 | for (int i = n - 1; i >= 0; i--) { 24 | swap(arr[0], arr[i]); 25 | heapify(arr, i, 0); 26 | } 27 | } 28 | 29 | void printArray(int arr[], int n) { 30 | for (int i = n-1; i >=0; i--) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | int main() { 36 | int arr[6] = {4,5,0,1,2,3}; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | heapSort(arr, n); 39 | cout << "Sorted array is :" < self.right_pointer: 12 | raise StopIteration 13 | left_square = self.sorted_array[self.left_pointer] ** 2 14 | right_square = self.sorted_array[self.right_pointer] ** 2 15 | if left_square > right_square: 16 | self.left_pointer += 1 17 | return left_square 18 | else: 19 | self.right_pointer -= 1 20 | return right_square 21 | 22 | class Solution: 23 | def sortedSquares(self, A: List[int]) -> List[int]: 24 | return_array = [0] * len(A) 25 | write_pointer = len(A) - 1 26 | for square in SquaresIterator(A): 27 | return_array[write_pointer] = square 28 | write_pointer -= 1 29 | return return_array -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/Remove duplicates from an unsorted linked list/readme.md: -------------------------------------------------------------------------------- 1 | ## Remove duplicate element from unsorted Linked List 2 | 3 | Given an unsorted linked list of N nodes. The task is to remove duplicate elements from this unsorted Linked List. When a value appears in multiple nodes, the node which appeared first should be kept, all others duplicates are to be removed. 4 | 5 | Example 1: 6 | ```C 7 | Input: 8 | N = 4 9 | value[] = {5,2,2,4} 10 | Output: 5 2 4 11 | Explanation:Given linked list elements are 12 | 5->2->2->4, in which 2 is repeated only. 13 | So, we will delete the extra repeated 14 | elements 2 from the linked list and the 15 | resultant linked list will contain 5->2->4 16 | ``` 17 | 18 | Example 2: 19 | ```C 20 | Input: 21 | N = 5 22 | value[] = {2,2,2,2,2} 23 | Output: 2 24 | Explanation:Given linked list elements are 25 | 2->2->2->2->2, in which 2 is repeated. So, 26 | we will delete the extra repeated elements 27 | 2 from the linked list and the resultant 28 | linked list will contain only 2. 29 | ``` 30 | Expected Time Complexity: O(N) 31 | Expected Auxiliary Space: O(N) 32 | 33 | Constraints: 34 | 1 <= size of linked lists <= 10^6 35 | 0 <= numbers in list <= 10^4 36 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/Printing all solutions in n-queen problems/readme.md: -------------------------------------------------------------------------------- 1 | The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. 2 | The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. 3 | The task is to print all solutions in N-Queen Problem. Each solution contains distinct board configurations of the N-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For the example above solution is written as [[2 4 1 3 ] [3 1 4 2 ]]. The solution discussed here is an extension of the same approach. 4 | 5 | 6 | Backtracking Algorithm 7 | 8 | The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false. -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/counting_islands_in_graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void BFS(vector adj[], int s, bool visited[]) 5 | { queue q; 6 | 7 | visited[s] = true; 8 | q.push(s); 9 | 10 | while(q.empty()==false) 11 | { 12 | int u = q.front(); 13 | q.pop(); 14 | 15 | for(int v:adj[u]){ 16 | if(visited[v]==false){ 17 | visited[v]=true; 18 | q.push(v); 19 | } 20 | } 21 | } 22 | } 23 | 24 | int BFSDin(vector adj[], int V){ 25 | bool visited[V]; int count=0; 26 | for(int i = 0;i adj[], int u, int v){ 38 | adj[u].push_back(v); 39 | adj[v].push_back(u); 40 | } 41 | 42 | int main() 43 | { 44 | int V=7; 45 | vector adj[V]; 46 | addEdge(adj,0,1); 47 | addEdge(adj,0,2); 48 | addEdge(adj,2,3); 49 | addEdge(adj,1,3); 50 | addEdge(adj,4,5); 51 | addEdge(adj,5,6); 52 | addEdge(adj,4,6); 53 | 54 | cout << "Number of islands: "< 3 | using namespace std; 4 | 5 | int maxSum(int stack1[], int stack2[], int stack3[], int n1, 6 | int n2, int n3) 7 | { 8 | int sum1 = 0, sum2 = 0, sum3 = 0; 9 | 10 | for (int i = 0; i < n1; i++) 11 | sum1 += stack1[i]; 12 | 13 | for (int i = 0; i < n2; i++) 14 | sum2 += stack2[i]; 15 | 16 | for (int i = 0; i < n3; i++) 17 | sum3 += stack3[i]; 18 | 19 | int top1 = 0, top2 = 0, top3 = 0; 20 | while (1) { 21 | if (top1 == n1 || top2 == n2 || top3 == n3) 22 | return 0; 23 | 24 | if (sum1 == sum2 && sum2 == sum3) 25 | return sum1; 26 | 27 | if (sum1 >= sum2 && sum1 >= sum3) 28 | sum1 -= stack1[top1++]; 29 | else if (sum2 >= sum1 && sum2 >= sum3) 30 | sum2 -= stack2[top2++]; 31 | else if (sum3 >= sum2 && sum3 >= sum1) 32 | sum3 -= stack3[top3++]; 33 | } 34 | } 35 | 36 | int main() 37 | { 38 | int stack1[] = { 3, 2, 1, 1, 1 }; 39 | int stack2[] = { 4, 3, 2 }; 40 | int stack3[] = { 1, 1, 4, 1 }; 41 | 42 | int n1 = sizeof(stack1) / sizeof(stack1[0]); 43 | int n2 = sizeof(stack2) / sizeof(stack2[0]); 44 | int n3 = sizeof(stack3) / sizeof(stack3[0]); 45 | 46 | cout << maxSum(stack1, stack2, stack3, n1, n2, n3) 47 | << endl; 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Staircase/stair.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string ltrim(const string &); 6 | string rtrim(const string &); 7 | 8 | /* 9 | * Complete the 'staircase' function below. 10 | * 11 | * The function accepts INTEGER n as parameter. 12 | */ 13 | 14 | void staircase(int n) { 15 | int count = 1; 16 | while(n--){ 17 | for(int i = 0; i < n; i++){ 18 | cout << " "; 19 | } 20 | for(int j = n - count; j < n; j++){ 21 | cout << "#"; 22 | } 23 | cout << endl; 24 | count++; 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | string n_temp; 31 | getline(cin, n_temp); 32 | 33 | int n = stoi(ltrim(rtrim(n_temp))); 34 | 35 | staircase(n); 36 | 37 | return 0; 38 | } 39 | 40 | string ltrim(const string &str) { 41 | string s(str); 42 | 43 | s.erase( 44 | s.begin(), 45 | find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) 46 | ); 47 | 48 | return s; 49 | } 50 | 51 | string rtrim(const string &str) { 52 | string s(str); 53 | 54 | s.erase( 55 | find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), 56 | s.end() 57 | ); 58 | 59 | return s; 60 | } 61 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Matrix/Common element in all rows of given matrix/commonEle.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/ 2 | // Common Element in each row 3 | 4 | #include 5 | using namespace std; 6 | 7 | #define rep(i,a,b) for(int i=a; i=b; i--) 9 | 10 | #define vi vector 11 | #define pii pair 12 | #define vii vector 13 | #define vvi vector 14 | #define pb push_back 15 | #define ff first 16 | #define ss second 17 | #define ll long long 18 | 19 | 20 | void printCommonElements(vvi matrix){ 21 | int n=matrix.size(); 22 | int m=matrix[0].size(); 23 | 24 | unordered_map mp; 25 | 26 | rep(i, 0, m) 27 | mp[matrix[0][i]] = 1; 28 | 29 | rep(i, 1, n){ 30 | rep(j, 0, m){ 31 | if(mp[matrix[i][j]] == i) //check for repeated ele in same row 32 | mp[matrix[i][j]]++; 33 | if(i==n-1 and mp[matrix[i][j]]==n) 34 | cout< 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | // Function to find majority element in the array 9 | // a: input array 10 | // size: size of input array 11 | int majorityElement(int a[], int size) 12 | { 13 | int cnt=1; 14 | int ma=a[0]; 15 | for(int i=1;isize/2) return ma; 30 | else return -1; 31 | } 32 | }; 33 | 34 | // { Driver Code Starts. 35 | 36 | int main(){ 37 | 38 | int t; 39 | cin >> t; 40 | 41 | while(t--){ 42 | int n; 43 | cin >> n; 44 | int arr[n]; 45 | 46 | for(int i = 0;i> arr[i]; 48 | } 49 | Solution obj; 50 | cout << obj.majorityElement(arr, n) << endl; 51 | } 52 | 53 | return 0; 54 | } 55 | // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/Word break using backtracking/wb.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | int dictionaryContains(string &word) 7 | { 8 | string dictionary[] = {"mobile","samsung","sam","sung", 9 | "man","mango", "icecream","and", 10 | "go","i","love","ice","cream"}; 11 | int n = sizeof(dictionary)/sizeof(dictionary[0]); 12 | for (int i = 0; i < n; i++) 13 | if (dictionary[i].compare(word) == 0) 14 | return true; 15 | return false; 16 | } 17 | 18 | void wordBreakUtil(string str, int size, string result); 19 | 20 | void wordBreak(string str) 21 | { 22 | 23 | wordBreakUtil(str, str.size(), ""); 24 | } 25 | 26 | void wordBreakUtil(string str, int n, string result) 27 | { 28 | for (int i=1; i<=n; i++) 29 | { 30 | string prefix = str.substr(0, i); 31 | 32 | if (dictionaryContains(prefix)) 33 | { 34 | if (i == n) 35 | { 36 | result += prefix; 37 | cout << result << endl; 38 | return; 39 | } 40 | wordBreakUtil(str.substr(i, n-i), n-i, 41 | result + prefix + " "); 42 | } 43 | } 44 | } 45 | 46 | int main() 47 | { 48 | 49 | cout << "First Test:\n"; 50 | wordBreak("iloveicecreamandmango"); 51 | 52 | cout << "\nSecond Test:\n"; 53 | wordBreak("ilovesamsungmobile"); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Searching/recursiveBinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int arr[], int l, int r, int x); 5 | int binarySearch(int arr[], int l, int r, int x){ 6 | if(r>=l){ 7 | int mid = l+(r-l)/2; 8 | if(arr[mid]==x){ 9 | return mid; 10 | } 11 | if(arr[mid]>x){ 12 | return binarySearch(arr, l, mid-1, x); 13 | } 14 | return binarySearch(arr, mid+1, r, x); 15 | } 16 | return -1; 17 | } 18 | 19 | int main(){ 20 | int n, numToSearch; 21 | cout<<"Enter number of elements ?"<>n; 23 | int arr[n]; 24 | for(int i=0;i>arr[i]; 27 | } 28 | cout<<"Enter element to be searched ?"<>numToSearch; 30 | int m = sizeof(arr) / sizeof(arr[0]); 31 | int result = binarySearch(arr, 0, m-1, numToSearch); 32 | cout<<"*** Elements of Array ***"< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* left; 7 | Node* right; 8 | 9 | Node(int x){ 10 | data=x; 11 | left=right=NULL; 12 | } 13 | }; 14 | 15 | void LeftTree(Node* root,vector &ans){ 16 | if(!root){ 17 | return; 18 | } 19 | ans.push_back(root->data); 20 | LeftTree(root->left,ans); 21 | else if{ 22 | ans.push_back(root->data); 23 | LeftTree(root->right); 24 | } 25 | } 26 | 27 | void leaf(Node* root,vector &ans){ 28 | if(!root) return; 29 | Leaf(root->left,ans); 30 | if(!root->left && !root->right){ 31 | ans.push_back(root); 32 | } 33 | Leaf(root->right,ans); 34 | } 35 | 36 | void RightTree(Node* root,vector &ans){ 37 | if(!root){ 38 | return; 39 | } 40 | 41 | if{ 42 | RightTree(root->right,ans); 43 | ans.push_back(root->data); 44 | } 45 | } 46 | 47 | vector PrintBoundary(Node* root){ 48 | vector ans; 49 | ans.push_back(root->data); 50 | LeftTree(root->left,ans); 51 | Leaf(root,ans); 52 | RightTree(root->right,ans); 53 | return ans; 54 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Searching & Sorting/Merge Without Extra Space/Merge Without Extra Space.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | //User function template for C++ 6 | class Solution{ 7 | public: 8 | void merge(int arr1[], int arr2[], int n, int m) { 9 | // code here 10 | int low = 0; 11 | int high = n-1; 12 | 13 | while(arr1[high] > arr2[low]) 14 | { 15 | 16 | swap(arr1[high--], arr2[low++]); 17 | if(high<0 || low == m) break; 18 | 19 | } 20 | sort(arr1, arr1+n); 21 | sort(arr2, arr2+m); 22 | 23 | } 24 | }; 25 | 26 | // { Driver Code Starts. 27 | int main() { 28 | int t; 29 | cin >> t; 30 | while (t--) { 31 | int n, m, i; 32 | cin >> n >> m; 33 | int arr1[n], arr2[m]; 34 | for (i = 0; i < n; i++) { 35 | cin >> arr1[i]; 36 | } 37 | for (i = 0; i < m; i++) { 38 | cin >> arr2[i]; 39 | } 40 | Solution ob; 41 | ob.merge(arr1, arr2, n, m); 42 | for (i = 0; i < n; i++) { 43 | cout << arr1[i] << " "; 44 | } 45 | for (i = 0; i < m; i++) { 46 | cout << arr2[i] << " "; 47 | } 48 | cout << "\n"; 49 | } 50 | return 0; 51 | } // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/LinkedList Implementation/Stack using LinkedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct node 3 | { 4 | int data; 5 | struct node *next; 6 | };*top; 7 | void push() 8 | { 9 | int item; 10 | printf("\nenter the item:"); 11 | scanf("%d",&item); 12 | struct node *p= (struct node*)malloc(sizeof(struct node)); 13 | p->data = item; 14 | if(top == NULL) 15 | p->next = NULL; 16 | else 17 | p->next = top; 18 | top = p; 19 | } 20 | void pop() 21 | { 22 | struct node *temp=top; 23 | if(top == NULL) 24 | printf("\nStack is Empty\n"); 25 | else{ 26 | temp = top; 27 | top= temp->next; 28 | free(temp); 29 | } 30 | } 31 | void display() 32 | { 33 | struct node *temp=top; 34 | if(temp!=NULL) 35 | { 36 | while(temp!=NULL) 37 | { 38 | printf("%d",temp->data); 39 | temp=temp->next; 40 | } 41 | } 42 | else 43 | printf("stack is empty"); 44 | } 45 | void main() 46 | { 47 | int choice=0; 48 | do 49 | { 50 | printf("\n1.insert item \n2.delete item \n3.display \n4.exit"); 51 | printf("\nenter ur choice:"); 52 | scanf("%d",&choice); 53 | switch(choice) 54 | { 55 | case 1: 56 | push();break; 57 | case 2: 58 | pop();break; 59 | case 3: 60 | display();break; 61 | case 4: 62 | printf("Exit");break; 63 | default: 64 | printf("enter valid choice"); 65 | } 66 | }while(choice<4); 67 | } 68 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Strings/Sentence to Mobile Keypad Equivalent/README.md: -------------------------------------------------------------------------------- 1 | ## Sentence to Mobile Keypad Equivalent 2 | Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence. 3 | 4 | ![image](https://user-images.githubusercontent.com/76874556/136007454-ded9a228-0aa9-45fb-bcd1-6d8a59a90d9c.png) 5 | 6 | Example 1: 7 | 8 | Input : GEEKSFORGEEKS 9 | Output : 4333355777733366677743333557777 10 | 11 | For obtaining a number, we need to press a number corresponding to that character for number of times equal to position of the character. For example, for character C, we press number 2 three times and accordingly. 12 | 13 | Example 2: 14 | 15 | Input : HELLO WORLD 16 | Output : 4433555555666096667775553 17 | 18 | ### Approach 19 | Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad sequence. 20 | 21 | 1. For each character, store the sequence which should be obtained at its respective position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so on. 22 | 2. For each character, subtract ASCII value of ‘A’ and obtain the position in the array pointed by that character and add the sequence stored in that array to a string. 23 | 3. If the character is a space, store 0. 24 | 4. Print the overall sequence. 25 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Triplet Sum in Array/solution.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | //Function to find if there exists a triplet in the 10 | //array A[] which sums up to X. 11 | bool find3Numbers(int nums[], int n, int sum) 12 | { 13 | //Your Code Here 14 | if(n<3) 15 | return 0; 16 | 17 | sort(nums, nums+n); 18 | 19 | for(int i=0; i>T; 43 | while(T--) 44 | { 45 | int n,X; 46 | cin>>n>>X; 47 | int i,A[n]; 48 | for(i=0;i>A[i]; 50 | Solution ob; 51 | cout << ob.find3Numbers(A, n, X) << endl; 52 | } 53 | } 54 | // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Counting Valleys/Readme.md: -------------------------------------------------------------------------------- 1 | An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly STEPS steps, for every step it was noted if it was an uphill, , or a downhill, step. Hikes always start and end at sea level, and each step up or down represents a unit change in altitude. We define the following terms: 2 | 3 | A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. 4 | A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. 5 | Given the sequence of up and down steps during a hike, find and print the number of valleys walked through. 6 | The hiker first enters a valley units deep. Then they climb out and up onto a mountain units high. Finally, the hiker returns to sea level and ends the hike. 7 | 8 | Function Description 9 | 10 | 11 | countingValleys has the following parameter(s): 12 | 13 | int steps: the number of steps on the hike 14 | string path: a string describing the path 15 | Returns 16 | 17 | int: the number of valleys traversed 18 | Input Format 19 | 20 | The first line contains an integer , the number of steps in the hike. 21 | The second line contains a single string , of characters that describe the path. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Arrays/Union of two arrays/solution.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function template in C++ 9 | 10 | class Solution{ 11 | public: 12 | //Function to return the count of number of elements in union of two arrays. 13 | int doUnion(int a[], int n, int b[], int m) { 14 | //code here 15 | vector res; 16 | for(int i = 0; i> t; 39 | 40 | while(t--){ 41 | 42 | int n, m; 43 | cin >> n >> m; 44 | int a[n], b[m]; 45 | 46 | for(int i = 0;i> a[i]; 48 | 49 | for(int i = 0;i> b[i]; 51 | Solution ob; 52 | cout << ob.doUnion(a, n, b, m) << endl; 53 | 54 | } 55 | 56 | return 0; 57 | } // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/Cheapest Flights Within K Stops/Readme.md: -------------------------------------------------------------------------------- 1 | # Problem Statement 2 | ## Cheapest Flights Within K Stops 3 | 4 | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. 5 | 6 | You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | ``` 13 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 14 | Output: 200 15 | Explanation: The graph is shown. 16 | The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture. 17 | ``` 18 | Example 2: 19 | ``` 20 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 21 | Output: 500 22 | Explanation: The graph is shown. 23 | The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture. 24 | ``` 25 | 26 | Constraints: 27 | ``` 28 | 1 <= n <= 100 29 | 0 <= flights.length <= (n * (n - 1) / 2) 30 | flights[i].length == 3 31 | 0 <= fromi, toi < n 32 | fromi != toi 33 | 1 <= pricei <= 104 34 | There will not be any multiple flights between two cities. 35 | 0 <= src, dst, k < n 36 | src != dst 37 | ``` 38 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/BFS of a Graph/Readme.md: -------------------------------------------------------------------------------- 1 | ## BFS of graph 2 | # Problem Statement 3 | Given a directed graph. The task is to do Breadth First Traversal of this graph starting from 0. 4 | Note: One can move from node u to node v only if there's an edge from u to v and find the BFS traversal of the graph starting from the 0th vertex, from left to right according to the graph. Also, you should only take nodes directly or indirectly connected from Node 0 in consideration. 5 | 6 | 7 | Example 1: 8 | 9 | Input: 10 | 5 4 11 | 0 1 12 | 0 2 13 | 0 3 14 | 2 4 15 | 16 | Output: 0 1 2 3 4 17 | 18 | Explanation: 19 | 0 is connected to 1 , 2 , 3. 20 | 2 is connected to 4. 21 | so starting from 0, it will go to 1 then 2 then 3.After this 2 to 4, thus bfs will be 22 | 0 1 2 3 4. 23 | 24 | 25 | Your task: 26 | You don’t need to read input or print anything. Your task is to complete the function bfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the BFS traversal of the graph starting from the 0th vertex from left to right. 27 | 28 | 29 | Expected Time Complexity: O(V + E) 30 | 31 | Expected Auxiliary Space: O(V) 32 | 33 | **Constraints:** 34 | 35 | 1 ≤ V, E ≤ 104 36 | 37 | **Link** https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1 -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Binary trees/Boundary Traversal/readme.md: -------------------------------------------------------------------------------- 1 | Given a Binary Tree, find its Boundary Traversal. The traversal should be in the following order: 2 | 3 | Left boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree. 4 | Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary. 5 | Reverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes. 6 | Note: If the root doesn't have a left subtree or right subtree, then the root itself is the left or right boundary. 7 | 8 | Example 1: 9 | 10 | Input: 11 | 1 12 | / \ 13 | 2 3 14 | 15 | Output: 1 2 3 16 | Explanation: 17 | 18 | 19 | Example 2: 20 | 21 | Input: 22 | 20 23 | / \ 24 | 8 22 25 | / \ \ 26 | 4 12 25 27 | / \ 28 | 10 14 29 | 30 | Output: 20 8 4 10 14 25 22 31 | Explanation: 32 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Data Structures/Linked List/6-DeleteLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | void printList(Node* head) 11 | { 12 | while (head != NULL) { 13 | cout << head->data << " "; 14 | head = head->next; 15 | } 16 | } 17 | 18 | void insertAtEnd(Node* head,int x){ 19 | Node* temp = head; 20 | Node* new_Node = new Node(); 21 | new_Node->data=x; 22 | new_Node->next = NULL; 23 | 24 | if(head == NULL){ 25 | head = new_Node; 26 | return; 27 | } 28 | while(temp->next != NULL){ 29 | temp = temp->next; 30 | } 31 | temp->next = new_Node; 32 | return; 33 | } 34 | 35 | void deleteList(Node* &head){ 36 | Node* current = head; 37 | Node* next = NULL; 38 | 39 | while(current!=NULL){ 40 | next = current->next; 41 | delete(current); 42 | current = next; 43 | } 44 | 45 | head = NULL; 46 | } 47 | 48 | int main(){ 49 | Node* head = NULL; 50 | head = new Node(); 51 | head->data = 1; 52 | insertAtEnd(head,2); 53 | insertAtEnd(head,3); 54 | insertAtEnd(head,4); 55 | insertAtEnd(head,5); 56 | insertAtEnd(head,6); 57 | insertAtEnd(head,7); 58 | printList(head); 59 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int h,w; 8 | cin>>h>>w; 9 | vector> v; 10 | 11 | for(int i=0;i vv; 14 | for(int j=0;j>k; 24 | vv.push_back(k); 25 | } 26 | } 27 | v.push_back(vv); 28 | } 29 | int ar=0; 30 | int aa=h*w; 31 | for(int i=1;iv[i-1][j]) 37 | { 38 | ar=ar+v[i][j]-v[i-1][j]; 39 | } 40 | if(v[i][j]>v[i+1][j]) 41 | { 42 | ar=ar+v[i][j]-v[i+1][j]; 43 | } 44 | if(v[i][j]>v[i][j-1]) 45 | { 46 | ar=ar+v[i][j]-v[i][j-1]; 47 | } 48 | if(v[i][j]>v[i][j+1]) 49 | { 50 | ar=ar+v[i][j]-v[i][j+1]; 51 | } 52 | } 53 | //cout<0) and find a sequence a of length k such that: 5 | 6 | 1≤a1 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node* root; 7 | Node* next; 8 | }; 9 | 10 | Node* Intersection(Node* head1,Node* head2){ 11 | Node* ptr1=head1; 12 | Node* ptr2=head2; 13 | Node* head=NULL; 14 | Node* curr= NULL; 15 | 16 | while(ptr1 && ptr2){ 17 | if(ptr1->data==ptr2->data){ 18 | if(head==NULL){ 19 | Node* t= new Node(ptr1->data){ 20 | head=t; 21 | curr=t; 22 | } 23 | else{ 24 | Node* t= new Node(ptr->data){ 25 | curr->next=t; 26 | curr=curr->next; 27 | } 28 | 29 | ptr1=ptr1->next; 30 | ptr2=ptr2->next; 31 | } 32 | else{ 33 | if(ptr1->datadata){ 34 | ptr1=ptr1->next; 35 | } 36 | else{ 37 | ptr2=ptr2->next; 38 | } 39 | } 40 | 41 | } 42 | } 43 | return head; 44 | } 45 | 46 | Node* createNode(int data){ 47 | Node* head = new Node(data); 48 | } 49 | 50 | int main(){ 51 | createNode(1); 52 | createNode(3); 53 | Intersection(head1,head2); 54 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/word Ladder/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int ladderLength(string beginWord, string endWord, vector& wordList) 5 | { 6 | unordered_setdict(wordList.begin(),wordList.end()); 7 | if(dict.find(endWord)==dict.end()) 8 | { 9 | return 0; 10 | } 11 | queueq; 12 | q.push(beginWord); 13 | int steps=1; 14 | while(!q.empty()) 15 | { 16 | int n=q.size(); 17 | while(n) 18 | { 19 | string node=q.front(); 20 | q.pop(); 21 | if(node==endWord) 22 | { 23 | return steps; 24 | } 25 | for(int i=0;i> threeSum(vector& nums) 5 | { 6 | sort(nums.begin(),nums.end()); 7 | 8 | int n = nums.size(); 9 | vector>ans; 10 | 11 | if(n<2) 12 | return ans; 13 | 14 | for(int i=0; i0 && nums[i]!=nums[i-1])) 17 | { 18 | int low =i+1,hi=n-1,sum=0-nums[i]; 19 | while(lowtemp; 24 | temp.push_back(nums[i]); 25 | temp.push_back(nums[low]); 26 | temp.push_back(nums[hi]); 27 | ans.push_back(temp); 28 | while(low 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution { 6 | public: 7 | // Function to return a list containing the DFS traversal of the graph. 8 | vector vec; 9 | 10 | void dfs(int v, bool visited[], vector adj[]) 11 | { 12 | visited[v] = true; 13 | vec.push_back(v); 14 | for(auto x: adj[v]) 15 | if(!visited[x]) 16 | dfs(x, visited, adj); 17 | } 18 | vector dfsOfGraph(int V, vector adj[]) { 19 | bool visited[V] = {false}; 20 | dfs(0, visited, adj); 21 | return vec; 22 | 23 | // Code here 24 | 25 | } 26 | }; 27 | 28 | // { Driver Code Starts. 29 | int main() { 30 | int tc; 31 | cin >> tc; 32 | while (tc--) { 33 | int V, E; 34 | cin >> V >> E; 35 | 36 | vector adj[V]; 37 | 38 | for (int i = 0; i < E; i++) { 39 | int u, v; 40 | cin >> u >> v; 41 | adj[u].push_back(v); 42 | adj[v].push_back(u); 43 | } 44 | // string s1; 45 | // cin>>s1; 46 | Solution obj; 47 | vector ans = obj.dfsOfGraph(V, adj); 48 | for (int i = 0; i < ans.size(); i++) { 49 | cout << ans[i] << " "; 50 | } 51 | cout << endl; 52 | } 53 | return 0; 54 | } // } Driver Code Ends -------------------------------------------------------------------------------- /dsa-roadmaps/LeetCode Study Plan/Algorithms/ALgorithm-1/Day 3 - Two Pointers/167. Two Sum II - Input array is sorted/readme.md: -------------------------------------------------------------------------------- 1 | ## Two Sum II - Input Array is sorted 2 | ### Problem Statement 3 | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first < second <= numbers.length. 4 | 5 | Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2. 6 | 7 | The tests are generated such that there is exactly one solution. You may not use the same element twice. 8 | 9 | 10 | 11 | 12 | Example 1: 13 | ``` 14 | Input: numbers = [2,7,11,15], target = 9 15 | Output: [1,2] 16 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 17 | 18 | ``` 19 | 20 | Example 2: 21 | ``` 22 | Input: numbers = [2,3,4], target = 6 23 | Output: [1,3] 24 | Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. 25 | ``` 26 | 27 | Example 3: 28 | ``` 29 | Input: numbers = [-1,0], target = -1 30 | Output: [1,2] 31 | Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. 32 | ``` 33 | 34 | Constraints: 35 | ``` 36 | 2 <= numbers.length <= 3 * 104 37 | -1000 <= numbers[i] <= 1000 38 | numbers is sorted in non-decreasing order. 39 | -1000 <= target <= 1000 40 | The tests are generated such that there is exactly one solution. 41 | ``` 42 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/birds/readme.md: -------------------------------------------------------------------------------- 1 | A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page is always on the right side: 2 | 3 | image 4 | 5 | When they flip page , they see pages and . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is pages long, and a student wants to turn to page , what is the minimum number of pages to turn? They can start at the beginning or the end of the book. 6 | 7 | Given and , find and print the minimum number of pages that must be turned in order to arrive at page . 8 | 9 | Example 10 | 11 | 12 | 13 | Untitled Diagram(4).png 14 | 15 | Using the diagram above, if the student wants to get to page , they open the book to page , flip page and they are on the correct page. If they open the book to the last page, page , they turn page and are at the correct page. Return . 16 | 17 | Function Description 18 | 19 | Complete the pageCount function in the editor below. 20 | 21 | pageCount has the following parameter(s): 22 | 23 | int n: the number of pages in the book 24 | int p: the page number to turn to 25 | Returns 26 | 27 | int: the minimum number of pages to turn 28 | Input Format 29 | 30 | The first line contains an integer , the number of pages in the book. 31 | The second line contains an integer, , the page to turn to. -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/LinkedList Implementation/Queue using LinkedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct node 3 | { 4 | int data; 5 | struct node *next; 6 | }; 7 | struct node*front=NULL; 8 | struct node*rear=NULL; 9 | void enqueue() 10 | { 11 | int item; 12 | printf("Enter the item to be inserted:"); 13 | scanf("%d",&item); 14 | struct node *p=(struct node*)malloc(sizeof(struct node)); 15 | p->data=item; 16 | p->next=NULL; 17 | if(front == NULL) 18 | front = rear = p; 19 | else 20 | { 21 | rear -> next = p; 22 | rear= p; 23 | } 24 | } 25 | void dequeue() 26 | { 27 | struct node *temp=(struct node*)malloc(sizeof(struct node)); 28 | if(front==NULL) 29 | printf("Queue underflow"); 30 | else 31 | { 32 | temp=front; 33 | front=front->next; 34 | free(temp); 35 | } 36 | } 37 | void display() 38 | { 39 | struct node *temp=(struct node*)malloc(sizeof(struct node)); 40 | temp=front; 41 | if(front == NULL) 42 | printf("\nEmpty queue\n"); 43 | else 44 | { 45 | while(temp!= NULL) 46 | { 47 | printf("%d\n",temp-> data); 48 | temp= temp-> next; 49 | } 50 | } 51 | } 52 | void main() 53 | { 54 | int choice=0; 55 | do 56 | { 57 | printf("\n1.insert \n2.delete \n3.display \n4.exit"); 58 | printf("\nenter ur choice:"); 59 | scanf("%d",&choice); 60 | switch(choice) 61 | { 62 | case 1: 63 | enqueue();break; 64 | case 2: 65 | dequeue();break; 66 | case 3: 67 | display();break; 68 | case 4: 69 | printf("Exit");break; 70 | default: 71 | printf("enter valid choice"); 72 | } 73 | }while(choice<4); 74 | } 75 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Migratory Birds/readme.md: -------------------------------------------------------------------------------- 1 | A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page is always on the right side: 2 | 3 | image 4 | 5 | When they flip page , they see pages and . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is pages long, and a student wants to turn to page , what is the minimum number of pages to turn? They can start at the beginning or the end of the book. 6 | 7 | Given and , find and print the minimum number of pages that must be turned in order to arrive at page . 8 | 9 | Example 10 | 11 | 12 | 13 | Untitled Diagram(4).png 14 | 15 | Using the diagram above, if the student wants to get to page , they open the book to page , flip page and they are on the correct page. If they open the book to the last page, page , they turn page and are at the correct page. Return . 16 | 17 | Function Description 18 | 19 | Complete the pageCount function in the editor below. 20 | 21 | pageCount has the following parameter(s): 22 | 23 | int n: the number of pages in the book 24 | int p: the page number to turn to 25 | Returns 26 | 27 | int: the minimum number of pages to turn 28 | Input Format 29 | 30 | The first line contains an integer , the number of pages in the book. 31 | The second line contains an integer, , the page to turn to. -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/word Ladder/Readme.md: -------------------------------------------------------------------------------- 1 | # Word Ladder 2 | 3 | ## Problem Statement 4 | 5 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: 6 | 7 | * Every adjacent pair of words differs by a single letter. 8 | * Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. 9 | * sk == endWord 10 | 11 | Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. 12 | 13 | Example 1: 14 | ``` 15 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 16 | Output: 5 17 | Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. 18 | ``` 19 | Example 2: 20 | ``` 21 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] 22 | Output: 0 23 | Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. 24 | ``` 25 | Constraints: 26 | ``` 27 | 1 <= beginWord.length <= 10 28 | endWord.length == beginWord.length 29 | 1 <= wordList.length <= 5000 30 | wordList[i].length == beginWord.length 31 | beginWord, endWord, and wordList[i] consist of lowercase English letters. 32 | beginWord != endWord 33 | All the words in wordList are unique. 34 | ``` 35 | 36 | **Link** https://leetcode.com/problems/word-ladder/ 37 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Backtracking/N_queens/N_queens.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define N 4 5 | 6 | int board[N][N]; 7 | 8 | void printSolution(int board[N][N]) 9 | { 10 | for (int i = 0; i < N; i++) { 11 | for (int j = 0; j < N; j++) 12 | printf(" %d ", board[i][j]); 13 | printf("\n"); 14 | } 15 | } 16 | 17 | bool isSafe(int row, int col) 18 | { 19 | 20 | for (int i = 0; i < col; i++) 21 | if (board[row][i]) 22 | return false; 23 | 24 | for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) 25 | if (board[i][j]) 26 | return false; 27 | 28 | for (int i = row, j = col; j >= 0 && i < N; i++, j--) 29 | if (board[i][j]) 30 | return false; 31 | 32 | return true; 33 | } 34 | 35 | bool solveRec(int col) 36 | { 37 | if (col == N) 38 | return true; 39 | 40 | for (int i = 0; i < N; i++) { 41 | 42 | if (isSafe(i, col)) { 43 | board[i][col] = 1; 44 | 45 | if (solveRec(col + 1)) 46 | return true; 47 | 48 | board[i][col] = 0; 49 | } 50 | } 51 | 52 | return false; 53 | } 54 | 55 | bool solve() 56 | { 57 | if (solveRec(0) == false) { 58 | printf("Solution does not exist"); 59 | return false; 60 | } 61 | 62 | printSolution(board); 63 | return true; 64 | } 65 | 66 | int main() { 67 | 68 | solve(); 69 | return 0; 70 | 71 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Knapsack/Knapsackgreedy1.cpp: -------------------------------------------------------------------------------- 1 | //KNAPSACK PROBLEM USING GREEDY TECHNIQUE 2 | #include 3 | using namespace std; 4 | 5 | //PRE-PROCESSING PHASE DECLARATIONS 6 | #define MAX 100 7 | 8 | //DECLARING STRUCTURE FOR ITEM 9 | struct item 10 | { 11 | int weight; 12 | int profit; 13 | }items[MAX]; 14 | 15 | //DRIVER PROGRAM 16 | int main(){ 17 | cout<<"20BCE2946 - GREEDY METHOD 1"< Profit ): "<>s[i].weight; 26 | cin>>s[i].profit; 27 | } 28 | 29 | //sorting based on profit 30 | for(int i=0;iW){ 51 | sum-=s[i].weight; 52 | } 53 | } 54 | cout<<"Items to include : "; 55 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | void printList(Node* head) 11 | { 12 | while (head != NULL) { 13 | cout << head->data << " "; 14 | head = head->next; 15 | } 16 | } 17 | 18 | void insertAtEnd(Node* head,int key){ 19 | Node* temp = head; 20 | Node* new_Node = new Node(); 21 | new_Node->data=key; 22 | new_Node->next = NULL; 23 | 24 | if(head == NULL){ 25 | head = new_Node; 26 | return; 27 | } 28 | while(temp->next != NULL){ 29 | temp = temp->next; 30 | } 31 | temp->next = new_Node; 32 | return; 33 | } 34 | 35 | void insertAfter(Node* node,int key){ 36 | 37 | if(node == NULL){ 38 | return; 39 | } 40 | 41 | Node* new_Node = new Node(); 42 | new_Node->data=key; 43 | new_Node->next=node->next; 44 | node->next=new_Node; 45 | } 46 | 47 | int main(){ 48 | Node* head = NULL; 49 | Node* second = NULL; 50 | Node* third = NULL; 51 | 52 | head = new Node(); 53 | second = new Node(); 54 | third = new Node(); 55 | head->data = 1; 56 | 57 | second->data = 2; 58 | second->next = third; 59 | 60 | third->data = 3; 61 | third->next = NULL; 62 | 63 | insertAfter(third,6); 64 | insertAfter(second,7); 65 | 66 | insertAtEnd(head,2); 67 | insertAtEnd(head,3); 68 | insertAtEnd(head,4); 69 | insertAtEnd(head,5); 70 | 71 | printList(head); 72 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Linked List/FlattenLL/readme.md: -------------------------------------------------------------------------------- 1 | Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers: 2 | (i) a next pointer to the next node, 3 | (ii) a bottom pointer to a linked list where this node is head. 4 | Each of the sub-linked-list is in sorted order. 5 | Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. 6 | Note: The flattened list will be printed using the bottom pointer instead of next pointer. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: 13 | 5 -> 10 -> 19 -> 28 14 | | | | | 15 | 7 20 22 35 16 | | | | 17 | 8 50 40 18 | | | 19 | 30 45 20 | 21 | Output: 5-> 7-> 8- > 10 -> 19-> 20-> 22 | 22-> 28-> 30-> 35-> 40-> 45-> 50. 23 | 24 | Explanation: 25 | The resultant linked lists has every 26 | node in a single level. 27 | (Note: | represents the bottom pointer.) 28 | 29 | 30 | Example 2: 31 | 32 | Input: 33 | 5 -> 10 -> 19 -> 28 34 | | | 35 | 7 22 36 | | | 37 | 8 50 38 | | 39 | 30 40 | 41 | Output: 5->7->8->10->19->20->22->30->50 42 | 43 | Explanation: 44 | The resultant linked lists has every 45 | node in a single level. 46 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/flood fill algo/Readme.md: -------------------------------------------------------------------------------- 1 | # Flood Fill 2 | 3 | ## Problem Statement 4 | 5 | An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. 6 | 7 | You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc]. 8 | 9 | To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor. 10 | 11 | Return the modified image after performing the flood fill. 12 | 13 | Example 1: 14 | ``` 15 | Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2 16 | Output: [[2,2,2],[2,2,0],[2,0,1]] 17 | Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. 18 | Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. 19 | ``` 20 | Example 2: 21 | ``` 22 | Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2 23 | Output: [[2,2,2],[2,2,2]] 24 | ``` 25 | Constraints: 26 | ``` 27 | m == image.length 28 | n == image[i].length 29 | 1 <= m, n <= 50 30 | 0 <= image[i][j], newColor < 216 31 | 0 <= sr < m 32 | 0 <= sc < n 33 | ``` 34 | 35 | **link** https://leetcode.com/problems/flood-fill/ 36 | -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Algorithms/Graphs/Prims.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define V 7 8 | 9 | int minKey(int key[], bool mstSet[]) { 10 | int min = INT_MAX, min_index; 11 | for (int v = 0; v < V; v++) 12 | if (mstSet[v] == false && key[v] < min) 13 | min = key[v], min_index = v; 14 | return min_index; 15 | } 16 | 17 | int printMST(int parent[], int n, int graph[V][V]) { 18 | cout<<"Edge Weight\n"; 19 | for (int i = 1; i < V; i++) 20 | printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]); 21 | } 22 | void primMST(int graph[V][V]) { 23 | int parent[V]; 24 | int key[V]; 25 | bool mstSet[V]; 26 | for (int i = 0; i < V; i++) 27 | key[i] = INT_MAX, mstSet[i] = false; 28 | key[0] = 0; 29 | parent[0] = -1; 30 | for (int count = 0; count < V - 1; count++){ 31 | int u = minKey(key, mstSet); 32 | mstSet[u] = true; 33 | for (int v = 0; v < V; v++) 34 | if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) 35 | parent[v] = u, key[v] = graph[u][v]; 36 | } 37 | printMST(parent, V, graph); 38 | } 39 | int main() { 40 | //0-A,1-B,2-C,3-D,4-E,5-F,6-G 41 | int graph[V][V] = {{0,7,0,5,0,0,0}, 42 | {7,0,8,9,7,0,0}, 43 | {0,8,0,0,5,0,0}, 44 | {5,9,0,0,15,6,0}, 45 | {0,7,5,15,0,8,9}, 46 | {0,0,0,6,8,0,11}, 47 | {0,0,0,0,9,11,0}}; 48 | primMST(graph); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/birds/bird.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string ltrim(const string &); 6 | string rtrim(const string &); 7 | 8 | /* 9 | * Complete the 'pageCount' function below. 10 | * 11 | * The function is expected to return an INTEGER. 12 | * The function accepts following parameters: 13 | * 1. INTEGER n 14 | * 2. INTEGER p 15 | */ 16 | 17 | int pageCount(int n, int p) { 18 | int front = 0, back = 0; 19 | front = p/2; 20 | back = (n - p)/2; 21 | if(n%2 == 0){ 22 | if(n - p == 1) back++;} 23 | int fin; 24 | if(front < back){ 25 | fin = front; 26 | } 27 | else{ 28 | fin = back; 29 | } 30 | 31 | return fin; 32 | } 33 | 34 | int main() 35 | { 36 | ofstream fout(getenv("OUTPUT_PATH")); 37 | 38 | string n_temp; 39 | getline(cin, n_temp); 40 | 41 | int n = stoi(ltrim(rtrim(n_temp))); 42 | 43 | string p_temp; 44 | getline(cin, p_temp); 45 | 46 | int p = stoi(ltrim(rtrim(p_temp))); 47 | 48 | int result = pageCount(n, p); 49 | 50 | fout << result << "\n"; 51 | 52 | fout.close(); 53 | 54 | return 0; 55 | } 56 | 57 | string ltrim(const string &str) { 58 | string s(str); 59 | 60 | s.erase( 61 | s.begin(), 62 | find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) 63 | ); 64 | 65 | return s; 66 | } 67 | 68 | string rtrim(const string &str) { 69 | string s(str); 70 | 71 | s.erase( 72 | find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), 73 | s.end() 74 | ); 75 | 76 | return s; 77 | } 78 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/Clone Graph/Solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | void dfs(Node* curr,Node* node,vector& visited) 4 | { 5 | //Node* copy = new Node(node->val); 6 | visited[node->val] = node; 7 | for(auto ele: curr->neighbors) 8 | { 9 | if(visited[ele->val] == NULL) 10 | { 11 | Node *newnode = new Node(ele->val); 12 | (node->neighbors).push_back(newnode); 13 | dfs(ele,newnode,visited); 14 | } 15 | else 16 | (node->neighbors).push_back(visited[ele->val]); 17 | } 18 | } 19 | public: 20 | Node* cloneGraph(Node* node) { 21 | if(node==NULL) 22 | return NULL; 23 | 24 | vector visited(1000,NULL); 25 | Node* copy = new Node(node->val); 26 | visited[node->val] = copy; 27 | //Iterate for all neighbors 28 | for(auto curr: node->neighbors) 29 | { 30 | if(visited[curr->val] == NULL) 31 | { 32 | Node *newnode = new Node(curr->val); 33 | (copy->neighbors).push_back(newnode); 34 | dfs(curr,newnode,visited); 35 | } 36 | else 37 | (copy->neighbors).push_back(visited[curr->val]); 38 | } 39 | return copy; 40 | } 41 | }; 42 | 43 | 44 | static int fastio = []() { 45 | //#define endl '\n' 46 | std::ios::sync_with_stdio(false); 47 | //std::cin.tie(NULL); 48 | //std::cout.tie(0); 49 | return 0; 50 | }(); -------------------------------------------------------------------------------- /dsa-roadmaps/Beginners/Problem Solving/Migratory Birds/birds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string ltrim(const string &); 6 | string rtrim(const string &); 7 | 8 | /* 9 | * Complete the 'pageCount' function below. 10 | * 11 | * The function is expected to return an INTEGER. 12 | * The function accepts following parameters: 13 | * 1. INTEGER n 14 | * 2. INTEGER p 15 | */ 16 | 17 | int pageCount(int n, int p) { 18 | int front = 0, back = 0; 19 | front = p/2; 20 | back = (n - p)/2; 21 | if(n%2 == 0){ 22 | if(n - p == 1) back++;} 23 | int fin; 24 | if(front < back){ 25 | fin = front; 26 | } 27 | else{ 28 | fin = back; 29 | } 30 | 31 | return fin; 32 | } 33 | 34 | int main() 35 | { 36 | ofstream fout(getenv("OUTPUT_PATH")); 37 | 38 | string n_temp; 39 | getline(cin, n_temp); 40 | 41 | int n = stoi(ltrim(rtrim(n_temp))); 42 | 43 | string p_temp; 44 | getline(cin, p_temp); 45 | 46 | int p = stoi(ltrim(rtrim(p_temp))); 47 | 48 | int result = pageCount(n, p); 49 | 50 | fout << result << "\n"; 51 | 52 | fout.close(); 53 | 54 | return 0; 55 | } 56 | 57 | string ltrim(const string &str) { 58 | string s(str); 59 | 60 | s.erase( 61 | s.begin(), 62 | find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) 63 | ); 64 | 65 | return s; 66 | } 67 | 68 | string rtrim(const string &str) { 69 | string s(str); 70 | 71 | s.erase( 72 | find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), 73 | s.end() 74 | ); 75 | 76 | return s; 77 | } 78 | -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Graphs/Snakes and Ladders/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int snakesAndLadders(vector>& board) { 4 | 5 | int n = board.size(); 6 | vector b; 7 | 8 | int order = 0; 9 | for(int i = n - 1; i >= 0; i --){ 10 | if(order) 11 | reverse(board[i].begin(), board[i].end()); 12 | for(int j = 0; j < n; j ++){ 13 | if(board[i][j] != -1) 14 | board[i][j] --; 15 | b.push_back(board[i][j]); 16 | } 17 | order = 1 - order; 18 | } 19 | assert(b.size() == n * n); 20 | 21 | return bfs(b, 0, n * n - 1); 22 | } 23 | 24 | private: 25 | int bfs(const vector& b, int s, int t){ 26 | 27 | vector visited(b.size(), false); 28 | queue> q; 29 | q.push(make_pair(s, 0)); 30 | visited[s] = true; 31 | while(!q.empty()){ 32 | int pos = q.front().first; 33 | int step = q.front().second; 34 | q.pop(); 35 | 36 | if(pos == t) 37 | return step; 38 | 39 | for(int i = 1; i <= 6 && pos + i < b.size(); i ++){ 40 | int next = pos + i; 41 | if(b[next] != -1) 42 | next = b[next]; 43 | if(!visited[next]){ 44 | visited[next] = true; 45 | q.push(make_pair(next, step + 1)); 46 | } 47 | } 48 | } 49 | 50 | return -1; 51 | } 52 | }; -------------------------------------------------------------------------------- /dsa-roadmaps/Love Babbar Questions/Greedy/Shortest Job First/readme.md: -------------------------------------------------------------------------------- 1 | 2 | Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN is a non-preemptive algorithm. 3 | 4 | 5 | Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms. 6 | It is a Greedy Algorithm. 7 | It may cause starvation if shorter processes keep coming. This problem can be solved using the concept of ageing. 8 | It is practically infeasible as Operating System may not know burst time and therefore may not sort them. While it is not possible to predict execution time, several methods can be used to estimate the execution time for a job, such as a weighted average of previous execution times. SJF can be used in specialized environments where accurate estimates of running time are available. 9 | Algorithm: 10 | 11 | 12 | Sort all the process according to the arrival time. 13 | 14 | Then select that process which has minimum arrival time and minimum Burst time. 15 | 16 | After completion of process make a pool of process which after till the completion of previous process and select that process among the pool which is having minimum Burst time. 17 | 18 | 19 | How to compute below times in SJF using a program? 20 | 21 | 22 | Completion Time: Time at which process completes its execution. 23 | Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time 24 | Waiting Time(W.T): Time Difference between turn around time and burst time. 25 | Waiting Time = Turn Around Time – Burst Time --------------------------------------------------------------------------------