"
4 | labels: [
5 | "good first issue",
6 | "enhancement",
7 | "hacktoberfest",
8 | "priority:medium"
9 | ]
10 | body:
11 | - type: textarea
12 | id: Description
13 | attributes:
14 | label: "Description"
15 | description: Provide a detailed description of the issue. Include any relevant information, such as steps to reproduce the issue, expected behavior, and actual behavior.
16 | validations:
17 | required: true
18 | - type: textarea
19 | id: DSA_Problem
20 | attributes:
21 | label: "DSA Problem"
22 | description: Indicate here the DSA problem that the issue is related to.
23 | validations:
24 | required: true
25 |
--------------------------------------------------------------------------------
/LeetCode/Shuffle-the-Array/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [1470. Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/)
2 |
3 | Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
4 |
5 | Return the array in the form [x1,y1,x2,y2,...,xn,yn].
6 |
7 |
8 | ```exmaple 1
9 | Example 1:
10 |
11 | Input: nums = [2,5,1,3,4,7], n = 3
12 | Output: [2,3,5,4,1,7]
13 | Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
14 | ```
15 |
16 | ```example 2
17 | Example 2:
18 |
19 | Input: nums = [1,2,3,4,4,3,2,1], n = 4
20 | Output: [1,4,2,3,3,2,4,1]
21 | ```
22 |
23 | ```example 3
24 | Example 3:
25 |
26 | Input: nums = [1,1,2,2], n = 2
27 | Output: [1,2,1,2]
28 | ```
29 |
30 | ```constrants
31 | Constraints:
32 |
33 | 1 <= n <= 500
34 | nums.length == 2n
35 | 1 <= nums[i] <= 10^3
36 | ```
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 30-Days-DSA-Challenge
2 |
3 | Getting into Data Structure And Algorithms May Look Challenging.
4 |
5 | This is why this repository is here to help you with DSA problems and solutions to solve them.
6 |
7 | ## How To Get Started
8 |
9 | Problems are gotten from Leetcode, Hackerrank and other DSA platforms and structured to help you quickly find them.
10 |
11 | * find a related problem
12 | * Select the language you want to use in solving the problem
13 | * you'll find the code, a screenshot and a readMe containing the problem statement
14 |
15 |
16 | Contributors
17 |
18 |
19 |
20 |
21 |
22 |
23 | Happy Coding
24 |
--------------------------------------------------------------------------------
/LeetCode/Search-Insert-Position/Python/search_insert_position.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def searchInsert(self, nums, target):
3 | start, end = 0, len(nums) - 1
4 |
5 | while start <= end:
6 | mid = start + (end - start) // 2
7 |
8 | if nums[mid] == target:
9 | return mid # Target found at index mid
10 | elif nums[mid] < target:
11 | start = mid + 1 # Target is in the end half
12 | else:
13 | end = mid - 1 # Target is in the start half
14 |
15 | return start # Target not found, return the insertion point
16 | # Create an instance of the Solution class
17 | solution = Solution()
18 |
19 | # Example usage:
20 | nums = [1, 3, 5, 6]
21 | target = 5
22 | result = solution.searchInsert(nums, target)
23 | print("Result:", result) # Output: 2
24 |
--------------------------------------------------------------------------------
/LeetCode/Trapping-Rain-Water/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [42. Trapping rain water](https://leetcode.com/problems/trapping-rain-water/description/)
2 |
3 | Given `n` non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
4 |
5 | ### Example 1:
6 |
7 | 
8 |
9 | **Input**: height = [0,1,0,2,1,0,1,3,2,1,2,1]
10 | **Output**: 6
11 | **Explanation**: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
12 |
13 | ### Example 2:
14 |
15 | **Input**: height = [4,2,0,3,2,5]
16 | **Output**: 9
17 |
18 | ### Constraints:
19 |
20 | - `n == height.length`
21 | - `1 <= n <= 2 * 10^4`
22 | - `0 <= height[i] <= 10^5`
23 |
--------------------------------------------------------------------------------
/LeetCode/Concatenation-of-Array/javascript/main.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number[]}
4 | */
5 | var getConcatenation = (nums) => {
6 |
7 | let ans = [];
8 | let n = nums.length;
9 |
10 | for (let i = 0; i < n * 2; i++){
11 | if (i < n) {
12 | ans[i] = nums[i]
13 | }
14 | if (i > n - 1) {
15 | ans[i] = nums[i-n]
16 | }
17 | }
18 | return ans
19 |
20 | /*
21 | Solving withing the same array solution also works
22 | */
23 | // let n = nums.length;
24 |
25 | // for (let i = 0; i < n * 2; i++){
26 | // if (i < n) {
27 | // nums[i] = nums[i]
28 | // }
29 | // if (i > n - 1) {
30 | // nums[i] = nums[i-n]
31 | // }
32 | // }
33 | // return nums
34 | };
35 |
36 | console.log(getConcatenation([1,2,1]))
--------------------------------------------------------------------------------
/LeetCode/Container With Most Water/Problem.md:
--------------------------------------------------------------------------------
1 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
2 |
3 | Find two lines that together with the x-axis form a container, such that the container contains the most water.
4 |
5 | Return the maximum amount of water a container can store.
6 |
7 | Notice that you may not slant the container.
8 |
9 |
10 |
11 | Example 1:
12 |
13 |
14 | Input: height = [1,8,6,2,5,4,8,3,7]
15 | Output: 49
16 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
17 | Example 2:
18 |
19 | Input: height = [1,1]
20 | Output: 1
21 |
22 |
23 | Constraints:
24 |
25 | n == height.length
26 | 2 <= n <= 105
27 | 0 <= height[i] <= 104
--------------------------------------------------------------------------------
/LeetCode/Peak Element in Array/C++/PeakElementArray.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int findPeakElement(std::vector& nums) {
5 | int left = 0;
6 | int right = nums.size() - 1;
7 |
8 | while (left < right) {
9 | int mid = left + (right - left) / 2;
10 |
11 | if (nums[mid] < nums[mid + 1]) {
12 | // Move right to search in the right half
13 | left = mid + 1;
14 | } else {
15 | // Move left to search in the left half
16 | right = mid;
17 | }
18 | }
19 |
20 | // 'left' now points to a peak element
21 | return left;
22 | }
23 |
24 | int main() {
25 | std::vector nums = {1, 2, 3, 1};
26 | int peakIndex = findPeakElement(nums);
27 | std::cout << "Peak element is at index: " << peakIndex << std::endl;
28 |
29 | return 0;
30 | }
31 |
--------------------------------------------------------------------------------
/LeetCode/Remove-Duplicates-From-Sorted-List/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)
2 |
3 | Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
4 |
5 | **Example 1:**
6 |
7 | 
8 | ```example 1
9 | Input: head = [1,1,2]
10 | Output: [1,2]
11 | ```
12 |
13 | **Example 2:**
14 |
15 | 
16 | ```
17 | Input: head = [1,1,2,3,3]
18 | Output: 5, nums = [1,2,3]
19 | ```
20 |
21 | **Constraints:**
22 | - The number of nodes in the list is in the range [0, 300].
23 | - -100 <= Node.val <= 100
24 | - The list is guaranteed to be sorted in ascending order.
25 |
26 |
--------------------------------------------------------------------------------
/LeetCode/Two-Sum/python/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [ TWO SUM](https://leetcode.com/problems/two-sum/description/)
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 | Explanation: 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 | Example 3:
22 |
23 | Input: nums = [3,3], target = 6
24 | Output: [0,1]
25 |
26 |
27 | ## Constraints:
28 |
29 | 2 <= nums.length <= 104
30 | -109 <= nums[i] <= 109
31 | -109 <= target <= 109
32 | Only one valid answer exists.
--------------------------------------------------------------------------------
/LeetCode/Baseball-Game/javascript/main.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string[]} operations
3 | * @return {number}
4 | */
5 | var calPoints = (operations) => {
6 | let ops = operations;
7 | let record = [];
8 | sum = 0
9 |
10 | for (let i = 0; i < ops.length; i++){
11 |
12 | if (ops[i] == "+") {
13 | record.push(Number(record[record.length - 2]) + Number(record[record.length - 1]))
14 | }
15 | else if (ops[i] == "C") {
16 | record.pop()
17 | }
18 | else if (ops[i] == "D") {
19 | record.push(2 * Number(record[record.length - 1]))
20 | }
21 | else {
22 | record.push(Number(ops[i]))
23 | }
24 | }
25 |
26 | record.forEach((score) => {
27 | sum += score
28 | })
29 |
30 | return sum
31 | };
32 |
33 | console.log(calPoints(["5","2","C","D","+"]));
--------------------------------------------------------------------------------
/LeetCode/Two-Sum/javascript/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [ TWO SUM](https://leetcode.com/problems/two-sum/description/)
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 | Explanation: 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 | Example 3:
22 |
23 | Input: nums = [3,3], target = 6
24 | Output: [0,1]
25 |
26 |
27 | ## Constraints:
28 |
29 | 2 <= nums.length <= 104
30 | -109 <= nums[i] <= 109
31 | -109 <= target <= 109
32 | Only one valid answer exists.
--------------------------------------------------------------------------------
/LeetCode/Reverse Nodes in k-Group/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 25. Reverse Nodes in k-Group
2 |
3 | **Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
4 |
5 | k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
6 |
7 | You may not alter the values in the list's nodes, only nodes themselves may be changed.**
8 |
9 | ### Examples
10 | ```
11 | Example 1:
12 | Input: head = [1,2,3,4,5], k = 2
13 | Output: [2,1,4,3,5]
14 |
15 | Example 2:
16 | Input: head = [1,2,3,4,5], k = 3
17 | Output: [3,2,1,4,5]
18 | ```
19 |
20 | ###Constraints:
21 | - The number of nodes in the list is n.
22 | - 1 <= k <= n <= 5000
23 | - 0 <= Node.val <= 1000
24 |
25 | https://leetcode.com/problems/reverse-nodes-in-k-group/description/
26 |
--------------------------------------------------------------------------------
/LeetCode/Product of Array Except Self/PROBLEM.md:
--------------------------------------------------------------------------------
1 | Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
2 |
3 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
4 |
5 | You must write an algorithm that runs in O(n) time and without using the division operation.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: nums = [1,2,3,4]
12 | Output: [24,12,8,6]
13 | Example 2:
14 |
15 | Input: nums = [-1,1,0,-3,3]
16 | Output: [0,0,9,0,0]
17 |
18 |
19 | Constraints:
20 |
21 | 2 <= nums.length <= 105
22 | -30 <= nums[i] <= 30
23 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
24 |
25 |
26 | Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
--------------------------------------------------------------------------------
/HackerRank/Max-Min-Sum/Javascript/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | process.stdin.resume();
4 | process.stdin.setEncoding("utf-8");
5 |
6 | let inputString = "";
7 | let currentLine = 0;
8 |
9 | process.stdin.on("data", function (inputStdin) {
10 | inputString += inputStdin;
11 | });
12 |
13 | process.stdin.on("end", function () {
14 | inputString = inputString.split("\n");
15 |
16 | main();
17 | });
18 |
19 | function readLine() {
20 | return inputString[currentLine++];
21 | }
22 |
23 | /*
24 | * Complete the 'miniMaxSum' function below.
25 | *
26 | * The function accepts INTEGER_ARRAY arr as parameter.
27 | */
28 |
29 | function miniMaxSum(arr) {
30 | // Write your code here
31 | }
32 |
33 | function main() {
34 | const arr = readLine()
35 | .replace(/\s+$/g, "")
36 | .split(" ")
37 | .map((arrTemp) => parseInt(arrTemp, 10));
38 |
39 | miniMaxSum(arr);
40 | }
41 |
--------------------------------------------------------------------------------
/.github/workflows/greetings.yml:
--------------------------------------------------------------------------------
1 | name: 'Greetings'
2 |
3 | on:
4 | fork:
5 | push:
6 | branches: [main]
7 | issues:
8 | types: [opened]
9 | pull_request_target:
10 | types: [opened]
11 |
12 | jobs:
13 | greetings:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v1
17 | - uses: EddieHubCommunity/gh-action-community/src/welcome@main
18 | with:
19 | github-token: ${{ secrets.GITHUB_TOKEN }}
20 | issue-message: 'Welcome, @${{ github.actor }}! Thanks for raising the issue! :nerd_face:'
21 | pr-message: 'Great job, @${{ github.actor }}! Thanks for the pull request! We'll review it as soon as possible.!'
22 | footer: 'Soon the maintainers/owner will review it and provide you with feedback/suggestions, Make sure to Star this awesome repository'
--------------------------------------------------------------------------------
/LeetCode/1382. Balance a Binary Search Tree/Problem.md:
--------------------------------------------------------------------------------
1 | # 1382. Balance a Binary Search Tree
2 |
3 | Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
4 |
5 | A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
6 |
7 |
8 | ## Input 1
9 |
10 | 
11 |
12 | Input: root = [1,null,2,null,3,null,4,null,null]
13 |
14 | Output: [2,1,3,null,null,null,4]
15 |
16 | Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
17 |
18 | ## Input 2
19 |
20 | 
21 |
22 | Input: root = [2,1,3]
23 |
24 | Output: [2,1,3]
25 |
26 | ### Constraints:
27 |
28 | The number of nodes in the tree is in the range [1, 104].
29 |
30 | 1 <= Node.val <= 105
--------------------------------------------------------------------------------
/LeetCode/3sum with multiplicity/Problem.md:
--------------------------------------------------------------------------------
1 | 3Sum with multiplicity
2 |
3 | Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.
4 |
5 | As the answer can be very large, return it modulo 109 + 7.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
12 | Output: 20
13 | Explanation:
14 | Enumerating by the values (arr[i], arr[j], arr[k]):
15 | (1, 2, 5) occurs 8 times;
16 | (1, 3, 4) occurs 8 times;
17 | (2, 2, 4) occurs 2 times;
18 | (2, 3, 3) occurs 2 times.
19 | Example 2:
20 |
21 | Input: arr = [1,1,2,2,2,2], target = 5
22 | Output: 12
23 | Explanation:
24 | arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
25 | We choose one 1 from [1,1] in 2 ways,
26 | and two 2s from [2,2,2,2] in 6 ways.
--------------------------------------------------------------------------------
/LeetCode/58-Length-Of-Last-Word/PROBLEM.md:
--------------------------------------------------------------------------------
1 | ## 58. [Length of Last Word](https://leetcode.com/problems/length-of-last-word)
2 |
3 | ### Description
4 | Given a string s consisting of words and spaces, return the length of the last word in the string.
5 | > A word is a maximal substring consisting of non-space characters only.
6 |
7 | ### Examples
8 |
9 | ```
10 | Input: s = "Hello World"
11 | Output: 5
12 | Explanation: The last word is "World" with length 5.
13 | Example 2:
14 |
15 | Input: s = " fly me to the moon "
16 | Output: 4
17 | Explanation: The last word is "moon" with length 4.
18 | Example 3:
19 |
20 | Input: s = "luffy is still joyboy"
21 | Output: 6
22 | Explanation: The last word is "joyboy" with length 6.
23 | ```
24 |
25 | ### Constraints
26 | ```
27 | 1 <= s.length <= 104
28 | s consists of only English letters and spaces ' '.
29 | There will be at least one word in s.
30 | ```
31 |
--------------------------------------------------------------------------------
/LeetCode/1382. Balance a Binary Search Tree/CPP/Problem.md:
--------------------------------------------------------------------------------
1 | # 1382. Balance a Binary Search Tree
2 |
3 | Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
4 |
5 | A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
6 |
7 |
8 | ## Input 1
9 |
10 | 
11 |
12 | Input: root = [1,null,2,null,3,null,4,null,null]
13 |
14 | Output: [2,1,3,null,null,null,4]
15 |
16 | Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
17 |
18 | ## Input 2
19 |
20 | 
21 |
22 | Input: root = [2,1,3]
23 |
24 | Output: [2,1,3]
25 |
26 | ### Constraints:
27 |
28 | The number of nodes in the tree is in the range [1, 104].
29 |
30 | 1 <= Node.val <= 105
--------------------------------------------------------------------------------
/LeetCode/148-SortList/Java/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public ListNode sortList(ListNode head) {
3 | int i =0;
4 | ListNode temp = head;
5 | int size = getSize(temp);
6 | int[] arr = new int[size];
7 | temp = head;
8 | while(temp!= null){
9 | arr[i++] = temp.val;
10 | temp = temp.next;
11 | }
12 | Arrays.sort(arr);
13 | temp = head;
14 | i=0;
15 | while(temp!= null){
16 | temp.val = arr[i++];
17 | temp = temp.next;
18 | }
19 |
20 | return head;
21 | }
22 | public static int getSize(ListNode head) {
23 | int size = 0;
24 | ListNode currentNode = head;
25 |
26 | while (currentNode != null) {
27 | size++;
28 | currentNode = currentNode.next;
29 | }
30 |
31 | return size;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/LeetCode/Monotonic Array/Python/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isMonotonic(self, nums: list[int]) -> bool:
3 | is_increasing = True # Indicates if the array is increasing.
4 | is_decreasing = True # Indicates if the array is decreasing.
5 |
6 | # Check if the array is either increasing or non-increasing.
7 | for i in range(1, len(nums)):
8 | # Check increasing condition.
9 | if nums[i] < nums[i - 1]:
10 | is_increasing = False
11 |
12 | # Check decreasing condition.
13 | elif nums[i] > nums[i - 1]:
14 | is_decreasing = False
15 |
16 | # If it is neither increasing nor decreasing then don't continue the loop.
17 | if not is_increasing and not is_decreasing:
18 | break
19 |
20 | return is_increasing or is_decreasing # Return true if either condition is met
--------------------------------------------------------------------------------
/LeetCode/Two-Sum/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 1. Two Sum
2 |
3 | Given an array of integers `nums` and an integer `target`, you need to return the indices of two numbers in the array such that they add up to the `target` value.
4 |
5 | You may assume that each input will 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 | ## Examples
10 |
11 | ### Example 1:
12 |
13 | Input: `nums = [2,7,11,15]`, `target = 9`
14 | Output: `[0,1]`
15 | Explanation: 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 | ## Constraints
28 |
29 | - `2 <= nums.length <= 10^4`
30 | - `-10^9 <= nums[i] <= 10^9`
31 | - `-10^9 <= target <= 10^9`
32 | - Only one valid answer exists.
33 |
--------------------------------------------------------------------------------
/LeetCode/Longest-Substring_Without-Repeating-Characters/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [3. Longest substring without repeating characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
2 |
3 | Given a string `s`, find the length of the longest substring without repeating characters.
4 |
5 | ### Example 1:
6 |
7 | Input: s = `"abcabcbb"`
8 | Output: 3
9 | Explanation: The answer is `"abc"`, with the length of 3.
10 |
11 | ### Example 2:
12 |
13 | Input: s = `"bbbbb"`
14 | Output: 1
15 | Explanation: The answer is `"b"`, with the length of 1.
16 |
17 | ### Example 3:
18 |
19 | Input: s = `"pwwkew"`
20 | Output: 3
21 | Explanation: The answer is `"wke"`, with the length of 3.
22 | Notice that the answer must be a substring, `"pwke"` is a subsequence and not a substring.
23 |
24 | ### Constraints:
25 |
26 | - `0 <= s.length <= 5 \* 104`
27 | - `s` consists of English letters, digits, symbols and spaces.
28 |
--------------------------------------------------------------------------------
/LeetCode/Zigzag-Conversion/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 6. Zigzag Conversion
2 |
3 | The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
4 | - And then read line by line: `"PAHNAPLSIIGYIR"`
5 | - Write the code that will take a string and make this conversion given a number of rows:
6 | - `string convert(string s, int numRows);`
7 |
8 | ## Examples
9 |
10 | ### Example 1:
11 |
12 | Input: `s = "PAYPALISHIRING"`, `numRows = 4`
13 | Output: `"PAHNAPLSIIGYIR"`
14 |
15 | ### Example 2:
16 |
17 | Input: `s = "PAYPALISHIRING"`, `numRows = 4`
18 | Output: `numRows = 4`
19 |
20 | ### Example 3:
21 |
22 | Input: `s = "A"`, `numRows = 1`
23 | Output: `"A"`
24 |
25 | ## Constraints
26 |
27 | * `1 <= s.length <= 1000`
28 | - `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
29 | - `1 <= numRows <= 1000`
--------------------------------------------------------------------------------
/GeeksForGeeks/Longest-Common-Subsequence/C++/solution.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Solution
5 | {
6 | public:
7 | // Function to find the length of longest common subsequence in two strings.
8 | int lcs(int m, int n, string s1, string s2)
9 | {
10 | vector> dp(m + 1, vector(n + 1, -1));
11 |
12 | for (int i = 0; i <= m; i++)
13 | {
14 | for (int j = 0; j <= n; j++)
15 | {
16 | if (i == 0 || j == 0)
17 | {
18 | dp[i][j] = 0;
19 | continue;
20 | }
21 |
22 | if (s1[i - 1] == s2[j - 1])
23 | dp[i][j] = 1 + dp[i - 1][j - 1];
24 | else
25 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
26 | }
27 | }
28 |
29 | return dp[m][n];
30 | }
31 | };
--------------------------------------------------------------------------------
/LeetCode/Rotate Array/PROBLEM.md:
--------------------------------------------------------------------------------
1 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: nums = [1,2,3,4,5,6,7], k = 3
8 | Output: [5,6,7,1,2,3,4]
9 | Explanation:
10 | rotate 1 steps to the right: [7,1,2,3,4,5,6]
11 | rotate 2 steps to the right: [6,7,1,2,3,4,5]
12 | rotate 3 steps to the right: [5,6,7,1,2,3,4]
13 | Example 2:
14 |
15 | Input: nums = [-1,-100,3,99], k = 2
16 | Output: [3,99,-1,-100]
17 | Explanation:
18 | rotate 1 steps to the right: [99,-1,-100,3]
19 | rotate 2 steps to the right: [3,99,-1,-100]
20 |
21 |
22 | Constraints:
23 |
24 | 1 <= nums.length <= 105
25 | -231 <= nums[i] <= 231 - 1
26 | 0 <= k <= 105
27 |
28 |
29 | Follow up:
30 |
31 | Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
32 | Could you do it in-place with O(1) extra space?
33 |
34 |
35 | Difficulty - Medium
--------------------------------------------------------------------------------
/LeetCode/Strictly-Palindromic-Number/Problem.MD:
--------------------------------------------------------------------------------
1 | # 2396. Strictly Palindromic Number
2 | ```
3 | An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.
4 |
5 | Given an integer n, return true if n is strictly palindromic and false otherwise.
6 |
7 | A string is palindromic if it reads the same forward and backward.
8 | ```
9 |
10 |
11 |
12 | ## Example 1:
13 | ```
14 | Input: n = 9
15 | Output: false
16 | Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.
17 | In base 3: 9 = 100 (base 3), which is not palindromic.
18 | Therefore, 9 is not strictly palindromic so we return false.
19 | Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.
20 | ```
21 | ## Example 2:
22 | ```
23 | Input: n = 4
24 | Output: false
25 | Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.
26 | Therefore, we return false.
27 | ```
--------------------------------------------------------------------------------
/LeetCode/946. Validate Stack Sequences/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 946. Validate Stack Sequences
2 |
3 | Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
4 |
5 | ## Examples
6 |
7 | ### Example 1:
8 |
9 | Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
10 | Output: true
11 | Explanation: We might do the following sequence:
12 | push(1), push(2), push(3), push(4),
13 | pop() -> 4,
14 | push(5),
15 | pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
16 |
17 | ### Example 2:
18 |
19 | Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
20 | Output: false
21 | Explanation: 1 cannot be popped before 2.
22 |
23 |
24 | ## Constraints
25 |
26 | 1 <= pushed.length <= 1000
27 | 0 <= pushed[i] <= 1000
28 | All the elements of pushed are unique.
29 | popped.length == pushed.length
30 | popped is a permutation of pushed.
31 |
--------------------------------------------------------------------------------
/LeetCode/15-3Sum/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 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 | **Example 1:**
6 |
7 | Input: nums = [-1,0,1,2,-1,-4]
8 | Output: [[-1,-1,2],[-1,0,1]]
9 | Explanation:
10 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
11 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
12 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
13 | The distinct triplets are [-1,0,1] and [-1,-1,2].
14 | _Notice that the order of the output and the order of the triplets does not matter._
15 |
16 | **Example 2:**
17 |
18 | Input: nums = [0,1,1]
19 | Output: []
20 | Explanation: The only possible triplet does not sum up to 0.
21 |
22 | **Example 3:**
23 |
24 | Input: nums = [0,0,0]
25 | Output: [[0,0,0]]
26 | Explanation: The only possible triplet sums up to 0.
27 |
28 | **Constraints:**
29 |
30 | `3 <= nums.length <= 3000`
31 | `-105 <= nums[i] <= 105`
32 |
--------------------------------------------------------------------------------
/LeetCode/48.Rotate Image/python/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def transpose(self, arr):
3 | for i in range(len(arr)):
4 | for j in range(i):
5 | temp = arr[i][j]
6 | arr[i][j] = arr[j][i]
7 | arr[j][i] = temp
8 |
9 | def reverse(self, arr):
10 | for r in range(len(arr)):
11 | left = 0
12 | right = len(arr) - 1
13 | while left < right:
14 | temp = arr[r][left]
15 | arr[r][left] = arr[r][right]
16 | arr[r][right] = temp
17 | left += 1
18 | right -= 1
19 |
20 | def rotate(self, matrix):
21 | self.transpose(matrix)
22 | self.reverse(matrix)
23 |
24 | def main():
25 | solution = Solution()
26 | arr = [[1,2,3],[4,5,6],[7,8,9]] #Example case hardcoded
27 | solution.rotate(arr)
28 | print(arr)
29 |
30 | if __name__ =="__main__":
31 | main()
--------------------------------------------------------------------------------
/LeetCode/Concatenation-of-Array/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [1929. Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/)
2 |
3 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
4 |
5 | Specifically, ans is the concatenation of two nums arrays.
6 |
7 | Return the array ans.
8 |
9 | ```example
10 | Example 1:
11 |
12 | Input: nums = [1,2,1]
13 | Output: [1,2,1,1,2,1]
14 | Explanation: The array ans is formed as follows:
15 | - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
16 | - ans = [1,2,1,1,2,1]
17 | Example 2:
18 |
19 | Input: nums = [1,3,2,1]
20 | Output: [1,3,2,1,1,3,2,1]
21 | Explanation: The array ans is formed as follows:
22 | - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
23 | - ans = [1,3,2,1,1,3,2,1]
24 |
25 |
26 | Constraints:
27 |
28 | n == nums.length
29 | 1 <= n <= 1000
30 | 1 <= nums[i] <= 1000
31 |
32 | ```
33 |
--------------------------------------------------------------------------------
/LeetCode/Strictly-Palindromic-Number/C++/Solution.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Solution {
5 | public:
6 | bool isStrictlyPalindromic(int n) {
7 | for(int i=2; i<=n; ++i) {
8 | string s = convertToBase(n,i);
9 | if(!isPalindrome(s)) {
10 | return false;
11 | }
12 | }
13 | return true;
14 | }
15 |
16 | bool isPalindrome(string s) {
17 | for(int i=0, j=s.size()-1; i 0) {
30 | answer += to_string(number%base);
31 | number /= base;
32 | }
33 |
34 | reverse(answer.begin(), answer.end());
35 | return answer;
36 | }
37 | };
38 |
--------------------------------------------------------------------------------
/LeetCode/Trapping Rain Water/trapping-rain-water.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int trap(int[] height) {
3 | // calculate left max boundary array
4 | int leftMax[]= new int [height.length];
5 | leftMax[0]=height[0];
6 | for(int i=1;i=0;i--)
14 | {
15 | rightMax[i]=Math.max(height[i],rightMax[i+1]);
16 | }
17 | int trappedwater=0;
18 | for(int i=0;i
2 | using namespace std;
3 |
4 | class Solution {
5 | public:
6 | bool spaceoptimise2(vector &nums,int target){
7 | vector curr(target+1,0);
8 | curr[0]=1;
9 | int n=nums.size();
10 | for(int index=n-1;index>=1;index--){
11 | for(int t=target;t>=0;t--){
12 | bool include=0;
13 | if(t-nums[index]>=0)
14 | include=curr[t-nums[index]];
15 | bool exclude=curr[t];
16 | curr[t]=(include|| exclude);
17 | }
18 | }
19 | return curr[target];
20 | }
21 | bool canPartition(vector& nums) {
22 | int sum=0;
23 | for(int i=0;i 4,
14 | push(5),
15 | pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
16 |
17 | ### Example 2:
18 |
19 | Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
20 | Output: false
21 | Explanation: 1 cannot be popped before 2.
22 |
23 |
24 | ## Constraints
25 |
26 | 1 <= pushed.length <= 1000
27 | 0 <= pushed[i] <= 1000
28 | All the elements of pushed are unique.
29 | popped.length == pushed.length
30 | popped is a permutation of pushed.
31 |
--------------------------------------------------------------------------------
/LeetCode/Koko Eating Bananas/C++/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | long long getHoursToEatAll(vector&piles, int bananasPerHour)
4 | {
5 | long long totalHours = 0;
6 | for (int i = 0; i < piles.size(); i++)
7 | {
8 | int hoursToEatPile = ceil(piles[i] / (double)bananasPerHour);
9 | totalHours += hoursToEatPile;
10 | }
11 | return totalHours;
12 | }
13 |
14 | int minEatingSpeed(vector& piles, int targetHours)
15 | {
16 | int low = 1, high = *(max_element(piles.begin(), piles.end()));
17 | int ans = -1;
18 |
19 | while(low <= high)
20 | {
21 | int mid = low + (high - low) / 2;
22 | long long hoursToEatAll = getHoursToEatAll(piles, mid);
23 |
24 | if (hoursToEatAll <= targetHours)
25 | {
26 | ans = mid;
27 | high = mid - 1;
28 | }
29 | else low = mid + 1;
30 | }
31 | return ans;
32 | }
33 | };
--------------------------------------------------------------------------------
/LeetCode/Split-Array-Largest-Sum/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [410. Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/description/)
2 |
3 | Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
4 |
5 | Return the minimized largest sum of the split.
6 |
7 | A subarray is a contiguous part of the array.
8 |
9 |
10 |
11 | ```example 1
12 |
13 | Input: nums = [7,2,5,10,8], k = 2
14 | Output: 18
15 | Explanation: There are four ways to split nums into two subarrays.
16 | The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
17 | ```
18 |
19 | ```example 2
20 |
21 | Input: nums = [1,2,3,4,5], k = 2
22 | Output: 9
23 | Explanation: There are four ways to split nums into two subarrays.
24 | The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.
25 | ```
26 |
27 | ```constrants
28 | 1 <= nums.length <= 1000
29 | 0 <= nums[i] <= 106
30 | 1 <= k <= min(50, nums.length)
31 | ```
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: "DSA Issue Request (Bug)"
2 | description: Create a new ticket for a new DSA bug or correction request
3 | title: "[BUG] - "
4 | labels: [
5 | "DSA",
6 | "bug",
7 | "good first issue",
8 | "priority:high",
9 |
10 | ]
11 | body:
12 | - type: textarea
13 | id: Description
14 | attributes:
15 | label: "Description"
16 | description: Provide a detailed description of the bug or correction. Include any relevant information, such as steps to reproduce the bug, expected behavior, and actual behavior.
17 | validations:
18 | required: true
19 | - type: textarea
20 | id: DSA_Problem
21 | attributes:
22 | label: "DSA Problem"
23 | description: Indicate here the DSA problem that the issue is related to.
24 | validations:
25 | required: true
26 | - type: textarea
27 | id: Code
28 | attributes:
29 | label: "Code"
30 | description: Provide a code snippet of the code that is affected by the bug or correction.
31 | validations:
32 | required: false
33 |
--------------------------------------------------------------------------------
/LeetCode/Divide-2-Integers/problem.md:
--------------------------------------------------------------------------------
1 | # 29. Divide Two Integers
2 |
3 | Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
4 |
5 | The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
6 |
7 | Return the quotient after dividing dividend by divisor.
8 |
9 | Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
10 |
11 | # Examples
12 |
13 | Example 1:
14 |
15 | Input: dividend = 10, divisor = 3
16 | Output: 3
17 | Explanation: 10/3 = 3.33333.. which is truncated to 3.
18 | Example 2:
19 |
20 | Input: dividend = 7, divisor = -3
21 | Output: -2
22 | Explanation: 7/-3 = -2.33333.. which is truncated to -2.
23 |
24 |
25 | # Constraints:
26 |
27 | -231 <= dividend, divisor <= 231 - 1
28 | divisor != 0
29 |
--------------------------------------------------------------------------------
/LeetCode/Sqrt(x)/C++/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Solution {
5 | public:
6 |
7 | long long int binarySearch(int n){
8 | int s=0;
9 | int e=n;
10 | long long int mid = s+(e-s)/2;
11 | long long int ans = -1;
12 |
13 | while(s<=e){
14 | long long int square = mid*mid;
15 | if(square == n){
16 | return mid;
17 | }
18 | if(square < n){
19 | ans = mid;
20 | s=mid+1;
21 | }
22 | else{
23 | e=mid-1;
24 | }
25 | mid = s+(e-s)/2;
26 | }
27 | return ans;
28 | }
29 | int mySqrt(int x) {
30 | return(binarySearch(x));
31 | }
32 | };
33 |
34 | int main(){
35 |
36 | Solution solution;
37 |
38 | int num = 8;
39 |
40 | long long result = solution.mySqrt(num);
41 |
42 | if (result)
43 | {
44 | cout<
2 |
3 | using namespace std;
4 |
5 | string simplifyPath(string path) {
6 | deque s;
7 | string t = "";
8 | for(int i=0;i 1) final.pop_back();
31 | return final;
32 | }
33 |
34 | int main() {
35 | string s;
36 | cout<<"Enter Path: ";
37 | cin>>s;
38 | cout<<"Simplified Path: "<
2 | using namespace std;
3 |
4 | class Solution
5 | {
6 | public:
7 | double findMedianSortedArrays(vector& nums1, vector& nums2)
8 | {
9 |
10 | nums1.insert(nums1.end(),nums2.begin(),nums2.end());
11 |
12 | int nums1_size = nums1.size();
13 | sort(nums1.begin(),nums1.end());
14 |
15 | if (nums1_size%2 !=0)
16 | {
17 | int mid = (nums1_size)/2;
18 | return (float) nums1[mid];
19 |
20 | }
21 |
22 | else
23 | {
24 | int m1 = (nums1_size)/2;
25 | int m2 = m1+1;
26 | float k1 = nums1[m1-1];
27 | float k2 = nums1[m2-1];
28 | float k = (k1+k2)/2;
29 | return k;
30 |
31 | }
32 |
33 |
34 | };
35 | };
36 |
37 |
38 | int main(){
39 |
40 | Solution solution;
41 | vector num1 = {1,3}; // can be from user
42 | vector num2 = {2};
43 |
44 | double result = solution.findMedianSortedArrays(num1,num2);
45 | cout<& a, int target) {
7 | long ans = 0, cnt[N]{};
8 | for (int &x : a) ++cnt[x];
9 | for (int i = 0; i < N; ++i)
10 | for (int j = i + 1; j < N; ++j) {
11 | int k = target - i - j;
12 | if (j < k && k < N)
13 | (ans += cnt[i] * cnt[j] * cnt[k]) %= M;
14 | }
15 | for (int i = 0; i < N; ++i) {
16 | int k = target - 2 * i;
17 | if (i < k && k < N) (ans += cnt[i] * (cnt[i] - 1) / 2 * cnt[k]) %= M;
18 | }
19 | for (int i = 0; i < N; ++i)
20 | if (target % 2 == i % 2) {
21 | int j = (target - i) / 2;
22 | if (i < j && j < N) (ans += cnt[i] * cnt[j] * (cnt[j] - 1) / 2) %= M;
23 | }
24 | if (target % 3 == 0) {
25 | int i = target / 3;
26 | if (0 <= i && i < N) (ans += (cnt[i] * (cnt[i] - 1) % M) * (cnt[i] - 2) / 6) %= M;
27 | }
28 | return ans;
29 | }
30 | };
--------------------------------------------------------------------------------
/LeetCode/66-Plus-One/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # 66. Plus One
2 | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
3 |
4 | Increment the large integer by one and return the resulting array of digits.
5 |
6 | ## Example:
7 |
8 | Input: digits = [1,2,3]
9 | Output: [1,2,4]
10 | Explanation: The array represents the integer 123.
11 | Incrementing by one gives 123 + 1 = 124.
12 | Thus, the result should be [1,2,4].
13 | Example 2:
14 |
15 | Input: digits = [4,3,2,1]
16 | Output: [4,3,2,2]
17 | Explanation: The array represents the integer 4321.
18 | Incrementing by one gives 4321 + 1 = 4322.
19 | Thus, the result should be [4,3,2,2].
20 | Example 3:
21 |
22 | Input: digits = [9]
23 | Output: [1,0]
24 | Explanation: The array represents the integer 9.
25 | Incrementing by one gives 9 + 1 = 10.
26 | Thus, the result should be [1,0].
27 |
28 |
29 | Constraints:
30 |
31 | 1 <= digits.length <= 100
32 | 0 <= digits[i] <= 9
33 | digits does not contain any leading 0's.
--------------------------------------------------------------------------------
/LeetCode/1.Two-sum-problem/readme.md:
--------------------------------------------------------------------------------
1 | # To Start The solving
2 |
3 | **This Problem was solved with C++, Use the below commands to start the project**
4 |
5 | ## Intuition
6 |
7 | This problem can be solved by nesting of two loops which will eventually increase the time complexity to O(n^2).
8 |
9 | To improve our runtime complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to get its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.
10 |
11 | We can reduce the lookup time from O(n) to O(1) by trading space for speed. A hash table is well suited for this purpose because it supports fast lookup in near constant time. I say "near" because if a collision occurred, a lookup could degenerate to O(n) time. However, lookup in a hash table should be amortized O(1) time as long as the hash function was chosen carefully.
12 |
13 | ## Time Complexity
14 |
15 | O(n)
16 |
17 | ## space complexity
18 |
19 | O(n)
20 |
21 | - **Make Sure to install c/c++ extension**
22 |
23 | - **To start the project**
24 |
25 | ```bash
26 | c++ solution.cpp
27 | ```
--------------------------------------------------------------------------------
/LeetCode/Product of Array Except Self/C++/ProductofArrayExceptSelf.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | class Solution {
5 | public:
6 | vector productExceptSelf(vector& nums) {
7 | vector output(nums.size());
8 | int prefix = 1;
9 | int suffix = 1;
10 | output[0] = 1;
11 | output[nums.size() - 1] = 1;
12 | for(int i = 1; i < nums.size(); i++){
13 | prefix = prefix * nums[i - 1];
14 | output[i] = prefix;
15 | }
16 | for(int i = 1; i < nums.size(); i++){
17 | suffix = suffix * nums[nums.size() - i];
18 | output[nums.size() - 1 - i] = output[nums.size() - 1 - i] * suffix;
19 | }
20 | return output;
21 | }
22 | };
23 |
24 | int main(){
25 |
26 | Solution solution;
27 | int n;
28 | cin>>n;
29 | vector nums(n);
30 | for (int i = 0; i < n; i++)
31 | {
32 | cin>>nums[i];
33 | }
34 | vector result = solution.productExceptSelf(nums);
35 | for (int i = 0; i < n; i++)
36 | {
37 | cout< stack = new Stack<>();
5 |
6 | // Iterate through all the tokens
7 | for (String token : tokens) {
8 | // Check symbol
9 | if (token.equals("+")) {
10 | // Push the result to the stack
11 | stack.push(stack.pop() + stack.pop());
12 | } else if (token.equals("-")) {
13 | int b = stack.pop();
14 | int a = stack.pop();
15 | stack.push(a - b);
16 | } else if (token.equals("*")) {
17 | stack.push(stack.pop() * stack.pop());
18 | } else if (token.equals("/")) {
19 | int b = stack.pop();
20 | int a = stack.pop();
21 | stack.push(a / b);
22 | } else { // If it is a number, parse it and push to the stack
23 | stack.push(Integer.parseInt(token));
24 | }
25 | }
26 | // Pop the result
27 | return stack.pop();
28 | }
29 | }
--------------------------------------------------------------------------------
/LeetCode/0054-spiral-matrix/C++/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector spiralOrder(vector>& matrix) {
4 | int rowStart = 0, colStart = 0, n = matrix[0].size(), m = matrix.size(), rowEnd = m -1, colEnd = n-1;
5 | vector ans;
6 | cout<rowEnd) return ans;
13 | for(int i = rowStart; i<=rowEnd; i++) {
14 | ans.push_back(matrix[i][colEnd]);
15 | }
16 | colEnd--;
17 | if(colStart>colEnd) return ans;
18 | for(int i = colEnd; i >= colStart; i--) {
19 | ans.push_back(matrix[rowEnd][i]);
20 | }
21 | rowEnd--;
22 | if(rowStart>rowEnd) return ans;
23 | for(int i = rowEnd; i>= rowStart ; i--) {
24 | ans.push_back(matrix[i][colStart]);
25 | }
26 | colStart++;
27 | }
28 | return ans;
29 | }
30 | };
31 |
--------------------------------------------------------------------------------
/LeetCode/Spiral Matrix/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an m x n matrix, return all elements of the matrix in spiral order.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13 | Output: [1,2,3,4,8,12,11,10,9,5,6,7]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | m == matrix.length
21 | n == matrix[i].length
22 | 1 <= m, n <= 10
23 | -100 <= matrix[i][j] <= 100
24 |
25 |
--------------------------------------------------------------------------------
/LeetCode/0054-spiral-matrix/C++/readme.md:
--------------------------------------------------------------------------------
1 | Medium
Given an m x n matrix, return all elements of the matrix in spiral order.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13 | Output: [1,2,3,4,8,12,11,10,9,5,6,7]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | m == matrix.length
21 | n == matrix[i].length
22 | 1 <= m, n <= 10
23 | -100 <= matrix[i][j] <= 100
24 |
25 |
--------------------------------------------------------------------------------
/LeetCode/94.Binary Tree Inorder Traversal/C++/readme.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root of a binary tree, return the inorder traversal of its nodes' values.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,null,2,3]
7 | Output: [1,3,2]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: root = []
13 | Output: []
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: root = [1]
19 | Output: [1]
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the tree is in the range
[0, 100].
27 | -100 <= Node.val <= 100
28 |
29 |
30 |
31 |
Follow up: Recursive solution is trivial, could you do it iteratively?
--------------------------------------------------------------------------------
/LeetCode/Trapping Rain Water/README.md:
--------------------------------------------------------------------------------
1 | Hard
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
7 | Output: 6
8 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: height = [4,2,0,3,2,5]
14 | Output: 9
15 |
16 |
17 |
18 |
Constraints:
19 |
20 |
21 | n == height.length
22 | 1 <= n <= 2 * 104
23 | 0 <= height[i] <= 105
24 |
25 |
--------------------------------------------------------------------------------
/LeetCode/1382. Balance a Binary Search Tree/CPP/main.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | public:
14 | vector nums;
15 | void inorder(TreeNode* root) {
16 | if (root != NULL) {
17 | inorder(root->left);
18 | nums.push_back(root->val);
19 | inorder(root->right);
20 | }
21 | }
22 | TreeNode* sortedArrayToBST(int left, int right) {
23 | if (left > right) {
24 | return NULL;
25 | }
26 | int mid = left + (right - left) / 2;
27 | TreeNode* newNode = new TreeNode(nums[mid]);
28 | newNode->left = sortedArrayToBST(left, mid - 1);
29 | newNode->right = sortedArrayToBST(mid + 1, right);
30 | return newNode;
31 | }
32 | TreeNode* balanceBST(TreeNode* root) {
33 | nums.clear();
34 | inorder(root);
35 | return sortedArrayToBST(0, nums.size() - 1);
36 | }
37 | };
--------------------------------------------------------------------------------
/LeetCode/Course Schedule/C++/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector findOrder(int numCourses, vector>& prerequisites) {
4 | // just print the topo sort if all indegree at the end are zero
5 |
6 | vectorindegree(numCourses, 0);
7 | vectoradj[numCourses];
8 | vectorans;
9 | for(auto it : prerequisites){
10 | adj[it[1]].push_back(it[0]); // created graph
11 | indegree[it[0]]++; // created indegree array
12 | }
13 | queueq;
14 | for(int i = 0; i < numCourses; i++){
15 | if(indegree[i] == 0){
16 | q.push(i);
17 | }
18 | }
19 | while(!q.empty()){
20 | int top = q.front();
21 | ans.push_back(top);
22 | q.pop();
23 | for(auto it : adj[top]){
24 | indegree[it]--;
25 | if(indegree[it] == 0){
26 | q.push(it);
27 | }
28 | }
29 | }
30 | for(int i = 0; i < numCourses; i++){
31 | if(indegree[i] != 0){
32 | vector dummy;
33 | return dummy;
34 | }
35 | }
36 | return ans;
37 | }
38 | };
39 |
--------------------------------------------------------------------------------
/LeetCode/Spiral Matrix/0054-spiral-matrix.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public List spiralOrder(int[][] matrix) {
3 | List ans = new ArrayList();
4 | int startrow=0,startcol=0,endrow=matrix.length-1,endcol=matrix[0].length-1;
5 | while(startrow<=endrow && startcol<=endcol)
6 | {
7 | for(int j=startcol;j<=endcol;j++)
8 | {
9 | ans.add(matrix[startrow][j]);
10 | }
11 | for(int i=startrow+1;i<=endrow;i++)
12 | {
13 | ans.add(matrix[i][endcol]);
14 | }
15 | for(int j=endcol-1;j>=startcol;j--)
16 | {
17 | if(startrow==endrow)
18 | {
19 | break;
20 | }
21 | ans.add(matrix[endrow][j]);
22 | }
23 | for(int i=endrow-1;i>=startrow+1;i--)
24 | {
25 | if(startcol==endcol)
26 | {
27 | break;
28 | }
29 | ans.add(matrix[i][startcol]);
30 | }
31 | startrow++;
32 | startcol++;
33 | endrow--;
34 | endcol--;
35 | }
36 | return ans;
37 |
38 | }
39 | }
--------------------------------------------------------------------------------
/LeetCode/Find-the-Maximum-Achievable-Number/Problem.md:
--------------------------------------------------------------------------------
1 | # Find the Maximum Achievable Number
2 | ```
3 | You are given two integers, num and t.
4 |
5 | An integer x is called achievable if it can become equal to num after applying the following operation no more than t times:
6 |
7 | Increase or decrease x by 1, and simultaneously increase or decrease num by 1.
8 | Return the maximum possible achievable number. It can be proven that there exists at least one achievable number.
9 | ```
10 |
11 |
12 | ## Example 1:
13 | ```
14 | Input: num = 4, t = 1
15 | Output: 6
16 | Explanation: The maximum achievable number is x = 6; it can become equal to num after performing this operation:
17 | 1- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5.
18 | It can be proven that there is no achievable number larger than 6.
19 | ```
20 |
21 | ## Example 2:
22 | ```
23 | Input: num = 3, t = 2
24 | Output: 7
25 | Explanation: The maximum achievable number is x = 7; after performing these operations, x will equal num:
26 | 1- Decrease x by 1, and increase num by 1. Now, x = 6 and num = 4.
27 | 2- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5.
28 | It can be proven that there is no achievable number larger than 7.
29 | ```
30 |
31 |
32 | ## Constraints:
33 | ```
34 | 1 <= num, t <= 50
35 | ```
--------------------------------------------------------------------------------
/LeetCode/Reverse Nodes in k-Group/C++/solution.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode() : val(0), next(nullptr) {}
7 | * ListNode(int x) : val(x), next(nullptr) {}
8 | * ListNode(int x, ListNode *next) : val(x), next(next) {}
9 | * };
10 | */
11 | class Solution {
12 | public:
13 | ListNode* reverseKGroup(ListNode* head, int k) {
14 | if (head == NULL || k == 1) return head;
15 |
16 | ListNode* dummy = new ListNode(0);
17 | dummy -> next = head;
18 | ListNode* curr = dummy;
19 | ListNode* nex = dummy;
20 | ListNode* prev = dummy;
21 | int count = 0;
22 |
23 | while(curr->next != NULL) {
24 | curr = curr -> next;
25 | count++;
26 | }
27 |
28 | while(count >= k) {
29 | curr = prev -> next;
30 | nex = curr -> next;
31 | for (int i = 1; i < k; i++) {
32 | curr-> next = nex -> next;
33 | nex -> next = prev -> next;
34 | prev -> next = nex;
35 | nex = curr -> next;
36 | }
37 | prev = curr;
38 | count -= k;
39 | }
40 | return dummy -> next;
41 | }
42 | };
--------------------------------------------------------------------------------
/LeetCode/N-Queens/PROBLEM.md:
--------------------------------------------------------------------------------
1 | ## Description of the Problem
2 |
3 | `The N-Queens puzzle is a classic problem in computer science and mathematics. In this puzzle, the goal is to place N chess queens on an N×N chessboard in such a way that no two queens threaten each other. This means that no two queens can be in the same row, column, or diagonal. Solving the N-Queens puzzle requires finding a configuration where all N queens can coexist peacefully on the board without threatening each other. It is a popular problem for algorithmic and combinatorial problem-solving exercises.`
4 |
5 | ## 51 N-queens
6 |
7 | **Problem Statement**
8 | `The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.`
9 |
10 | Given an integer `n`, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
11 |
12 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
13 | Example 1:
14 |
15 | **Example 1**
16 | Input: n = 4
17 | Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
18 | Explanation: There exist two distinct solutions to the 4-queens puzzle.
19 |
20 | **Example 2:**
21 | Input: n = 1
22 | Output: [["Q"]]
23 |
24 | **Constraints:**
25 | `1 <= n <= 9`
26 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Celebrity-Problem/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # The Celebrity Problem
2 | A celebrity is a person who is known to all but does not know anyone at a party. If you go to a party of N people, find if there is a celebrity in the party or not.
3 | A square NxN matrix M[][] is used to represent people at the party such that if an element of row i and column j is set to 1 it means ith person knows jth person. Here M[i][i] will always be 0.
4 | Note: Follow 0 based indexing.
5 | Follow Up: Can you optimize it to O(N)
6 |
7 |
8 | # Example 1:
9 |
10 | ### Input:
11 | N = 3
12 | M[][] = {{0 1 0},
13 | {0 0 0},
14 | {0 1 0}}
15 | ### Output: 1
16 | ### Explanation: 0th and 2nd person both
17 | know 1. Therefore, 1 is the celebrity.
18 |
19 | # Example 2:
20 |
21 | ### Input:
22 | N = 2
23 | M[][] = {{0 1},
24 | {1 0}}
25 | ### Output: -1
26 | ### Explanation: The two people at the party both
27 | know each other. None of them is a celebrity.
28 |
29 | # Your Task:
30 | You don't need to read input or print anything. Complete the function celebrity() which takes the matrix M and its size N as input parameters and returns the index of the celebrity. If no such celebrity is present, return -1.
31 |
32 |
33 | # Expected Time Complexity: O(N^2)
34 | # Expected Auxiliary Space: O(1)
35 |
36 |
37 | # Constraints:
38 | 2 <= N <= 3000
39 | 0 <= M[][] <= 1
--------------------------------------------------------------------------------
/LeetCode/Remove-Duplicates-From-Sorted-List/Java/Solution.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public static ListNode deleteDuplicates(ListNode head) {
3 |
4 | if(head==null || head.next==null)
5 | return head;
6 |
7 | ListNode prev = head;
8 | ListNode temp = head.next;
9 | while(temp!=null){
10 | if(temp.val==prev.val){
11 | prev.next = temp.next;
12 | temp = prev.next;
13 | }
14 | else {
15 | temp= temp.next;
16 | prev=prev.next;
17 | }
18 | }
19 | return head;
20 |
21 | }
22 |
23 | public static void main(String[] args) {
24 | ListNode head = new ListNode(1);
25 | head.next = new ListNode(1);
26 | head.next.next = new ListNode(2);
27 | head.next.next.next = null;
28 | System.out.println("Given List");
29 | printList(head);
30 | ListNode ans = deleteDuplicates(head);
31 | System.out.println("\nAnswer List");
32 | printList(ans);
33 | }
34 | private static void printList(ListNode head) {
35 | while(head!=null) {
36 | System.out.print(head.val + " ");
37 | head = head.next;
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/GeeksForGeeks/Celebrity-Problem/JAVA/Solution.java:
--------------------------------------------------------------------------------
1 | public class Solution
2 | {
3 | int celebrity(int m[][], int n)
4 | {
5 | int i=0,j=0,c=0;
6 | int k[] = new int[n];
7 | while (i0){
25 | c++;
26 | }
27 | }
28 | int l = -1;
29 | if (c==0){
30 | l=-1;
31 | }
32 | else{
33 | int min = k[0];
34 | for (i=1;i=k[i]){
36 | l=i;
37 | min=k[i];
38 | }
39 | }
40 | if (min==k[0]){
41 | l=0;
42 | }
43 | if (k[l]==0){
44 | for (i=0;i List[int]:
4 | def calculate(left, right, operator):
5 | results = []
6 | for l in left:
7 | for r in right:
8 | if operator == '+':
9 | results.append(l + r)
10 | elif operator == '-':
11 | results.append(l - r)
12 | elif operator == '*':
13 | results.append(l * r)
14 | return results
15 | if expression.isdigit():
16 | return [int(expression)]
17 |
18 | results = []
19 | for i in range(len(expression)):
20 | if expression[i] in "+-*":
21 | left = self.diffWaysToCompute(expression[:i])
22 | right = self.diffWaysToCompute(expression[i+1:])
23 | results.extend(calculate(left, right, expression[i]))
24 |
25 | return results
26 |
27 |
28 | # Example usage:
29 | solution = Solution()
30 | expression1 = "2-1-1"
31 | print(solution.diffWaysToCompute(expression1)) # Output: [0, 2]
32 |
33 | expression2 = "2*3-4*5"
34 | print(solution.diffWaysToCompute(expression2)) # Output: [-34, -14, -10, -10, 10]
--------------------------------------------------------------------------------
/LeetCode/241-Different-ways-to-add-paratheses/Python/README.md:
--------------------------------------------------------------------------------
1 | This code was done using python
2 |
3 | To run the above code in terminal type the below code
4 |
5 | Python main.py
6 |
7 | ## Approach:
8 |
9 | The approach to solving this problem is based on recursion and divide-and-conquer. We'll recursively break down the expression into smaller sub-expressions by finding operators, and then calculate the possible results for each combination of left and right sub-expressions.
10 |
11 | If the expression is just a single digit, we return it as a list with a single integer.
12 | Otherwise, we iterate through the expression and when we encounter an operator (+, -, or *), we split the expression into two parts: the left part before the operator and the right part after the operator.
13 | We recursively calculate the possible results for the left and right parts.
14 | For each pair of results from the left and right parts, we apply the operator to them and add the result to the final list of results.
15 | Finally, we return the list of all possible results.
16 |
17 | ## Complexity Analysis
18 |
19 | -Time complexity
20 | `O(3^n)`, where n is the number of operators in the expression
21 |
22 | -Space complexity
23 | `O(3^n)`
24 | This is because we store the results of all possible combinations in a list, and in the worst case, there can be 3^n different results.
25 |
26 |
--------------------------------------------------------------------------------
/HackerRank/Plus-Minus/Javascript/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | process.stdin.resume();
4 | process.stdin.setEncoding("utf-8");
5 |
6 | let inputString = "";
7 | let currentLine = 0;
8 |
9 | process.stdin.on("data", function (inputStdin) {
10 | inputString += inputStdin;
11 | });
12 |
13 | process.stdin.on("end", function () {
14 | inputString = inputString.split("\n");
15 |
16 | main();
17 | });
18 |
19 | function readLine() {
20 | return inputString[currentLine++];
21 | }
22 |
23 | /*
24 | * Complete the 'plusMinus' function below.
25 | *
26 | * The function accepts INTEGER_ARRAY arr as parameter.
27 | */
28 |
29 | function plusMinus(arr) {
30 | let denominator = arr.length;
31 | let count = 1 / denominator;
32 | let result = [0, 0, 0];
33 |
34 | for (let i = 0; i <= denominator; i++) {
35 | if (arr[i] > 0) {
36 | result[0] += count;
37 | } else if (arr[i] < 0) {
38 | result[1] += count;
39 | } else if (arr[i] == 0) {
40 | result[2] += count;
41 | }
42 | }
43 |
44 | result.forEach((num) => {
45 | console.log(num.toFixed(6));
46 | });
47 | }
48 |
49 | console.log(plusMinus([-4, 3, -9, 0, 4, 1]));
50 |
51 | function main() {
52 | const n = parseInt(readLine().trim(), 10);
53 |
54 | const arr = readLine()
55 | .replace(/\s+$/g, "")
56 | .split(" ")
57 | .map((arrTemp) => parseInt(arrTemp, 10));
58 |
59 | plusMinus(arr);
60 | }
61 |
--------------------------------------------------------------------------------
/LeetCode/Binary-Tree-Inorder-Traversal/C++/Solution.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | #include
13 | using namespace std;
14 |
15 | struct TreeNode {
16 | int val;
17 | TreeNode *left;
18 | TreeNode *right;
19 | TreeNode() : val(0), left(nullptr), right(nullptr) {}
20 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
21 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
22 | };
23 |
24 | class Solution {
25 | public:
26 | vector inorderTraversal(TreeNode* root) {
27 | vector res;
28 | traversal(root, res);
29 | return res;
30 | }
31 |
32 | void traversal(TreeNode* root, vector &res) {
33 | if (root == NULL)
34 | return;
35 |
36 | // First recur on left child
37 | traversal(root->left, res);
38 |
39 | // Then print the data of node
40 | res.push_back(root->val);
41 |
42 | // Now recur on right child
43 | traversal(root->right, res);
44 | }
45 | };
--------------------------------------------------------------------------------
/LeetCode/1.Two-sum-problem/C++/problem.md:
--------------------------------------------------------------------------------
1 | ## [0/1 Knapsack Problem(dynamic programming](https://leetcode.com/problems/two-sum/description/)
2 |
3 | ## Description
4 |
5 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
6 |
7 | You may assume that each input would have exactly one solution, and you may not use the same element twice.
8 |
9 | You can return the answer in any order.
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: nums = [2,7,11,15], target = 9
16 | Output: [0,1]
17 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
18 | Example 2:
19 |
20 | Input: nums = [3,2,4], target = 6
21 | Output: [1,2]
22 | Example 3:
23 |
24 | Input: nums = [3,3], target = 6
25 | Output: [0,1]
26 |
27 | ## Solution approach
28 |
29 | 1. Create an empty hash table to store elements and their indices.
30 | 2. Iterate through the array from left to right.
31 | 3. For each element nums[i], calculate the complement by subtracting it from the target: complement = target - nums[i].
32 | 4. Check if the complement exists in the hash table. If it does, we have found a solution.
33 | 5. If the complement does not exist in the hash table, add the current element nums[i] to the hash table with its index as the value.
34 | 6. Repeat steps 3-5 until we find a solution or reach the end of the array.
35 | 7. If no solution is found, return an empty array or an appropriate indicator.
--------------------------------------------------------------------------------
/LeetCode/53-Maximum-Subarray/C++/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
2 |
3 |
A subarray is a contiguous part of an array.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
9 | Output: 6
10 | Explanation: [4,-1,2,1] has the largest sum = 6.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [1]
16 | Output: 1
17 |
18 |
19 |
Example 3:
20 |
21 |
Input: nums = [5,4,-1,7,8]
22 | Output: 23
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= nums.length <= 105
30 | -104 <= nums[i] <= 104
31 |
32 |
33 |
34 |
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.
35 |
--------------------------------------------------------------------------------
/LeetCode/sliding-window-maximum/python/sliding.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | from typing import List
3 |
4 | class Solution:
5 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
6 | result = [] # Initialize an empty list to store maximum values.
7 | window = deque() # Create a deque to store indices of elements in the current window.
8 |
9 | for i, num in enumerate(nums):
10 | # Remove elements from the left end of the deque if they are out of the current window.
11 | while window and window[0] < i - k + 1:
12 | window.popleft()
13 |
14 | # Remove elements from the right end of the deque if they are smaller than the current element.
15 | while window and nums[window[-1]] < num:
16 | window.pop()
17 |
18 | # Add the current element's index to the deque.
19 | window.append(i)
20 |
21 | # If we have processed at least k elements (i.e., i >= k - 1), add the maximum value
22 | # in the current window (the first element of the deque) to the result list.
23 | if i >= k - 1:
24 | result.append(nums[window[0]])
25 |
26 | return result
27 |
28 | # Example usage:
29 | solution = Solution()
30 | nums = [1, 3, -1, -3, 5, 3, 6, 7]
31 | k = 3
32 | result = solution.maxSlidingWindow(nums, k)
33 | print("Maximum values in sliding window of size", k, "are:", result)
34 |
--------------------------------------------------------------------------------
/LeetCode/Jump-Game-II/PROBLEM.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
5 |
6 | Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
7 |
8 | 0 <= j <= nums[i] and
9 | i + j < n
10 | Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
11 |
12 |
13 | Example 1:
14 |
15 |
16 | Input: nums = [2,3,1,1,4]
17 | Output: 2
18 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
19 |
20 |
21 | Example 2:
22 |
23 |
24 | Input: nums = [2,3,0,1,4]
25 | Output: 2
26 |
27 |
28 | Constraints:
29 |
30 |
31 | 1 <= nums.length <= 10^4
32 | 0 <= nums[i] <= 1000
33 | - It's guaranteed that you can reach
nums[n-1].
34 |
35 |
--------------------------------------------------------------------------------
/LeetCode/Merge-Two-Sorted-Lists/python/main.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | # Definition for singly-linked list.
4 | class ListNode:
5 | def __init__(self, val=0, next=None):
6 | self.val = val
7 | self.next = next
8 |
9 | class Solution:
10 |
11 | def print_result(self):
12 | self.print_list(self.result)
13 |
14 | def print_list(self, head):
15 | if head is None:
16 | print()
17 | return
18 | print(head.val, end = " ")
19 | self.print_list(head.next)
20 |
21 | def create_list(self, idx, n, l):
22 | if idx == n:
23 | return None
24 | curr_node = ListNode(l[idx])
25 | curr_node.next = self.create_list(idx+1, n, l)
26 | return curr_node
27 |
28 | def __init__(self):
29 | list1 = [1, 2, 4, 5, 11, 23]
30 | list2 = [1, 3, 4, 6, 9, 12, 14, 29]
31 |
32 | self.result = self.mergeTwoLists(self.create_list(0, len(list1), list1),
33 | self.create_list(0, len(list2), list2))
34 |
35 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
36 | if list1 is None and list2 is None: return None
37 | elif list1 == None: return list2
38 | elif list2 == None: return list1
39 | elif list1.val <= list2.val:
40 | list1.next = self.mergeTwoLists(list1.next, list2)
41 | return list1
42 | list2.next = self.mergeTwoLists(list1, list2.next)
43 | return list2
44 |
45 | if __name__ == '__main__':
46 | s = Solution()
47 | s.print_result()
--------------------------------------------------------------------------------
/LeetCode/143-Maximum-SubArray/Java/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array nums, find the subarray with the largest sum, and return its sum.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
7 | Output: 6
8 | Explanation: The subarray [4,-1,2,1] has the largest sum 6.
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: nums = [1]
14 | Output: 1
15 | Explanation: The subarray [1] has the largest sum 1.
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: nums = [5,4,-1,7,8]
21 | Output: 23
22 | Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= nums.length <= 105
30 | -104 <= nums[i] <= 104
31 |
32 |
33 |
34 |
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.
35 |
--------------------------------------------------------------------------------
/LeetCode/142-Best-Time-To-Buy-And-Sell-Stocks/Java/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given an array prices where prices[i] is the price of a given stock on the ith day.
2 |
3 |
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
4 |
5 |
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: prices = [7,1,5,3,6,4]
11 | Output: 5
12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
13 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
14 |
15 |
16 |
Example 2:
17 |
18 |
Input: prices = [7,6,4,3,1]
19 | Output: 0
20 | Explanation: In this case, no transactions are done and the max profit = 0.
21 |
22 |
23 |
24 |
Constraints:
25 |
26 |
27 | 1 <= prices.length <= 105
28 | 0 <= prices[i] <= 104
29 |
30 |
--------------------------------------------------------------------------------
/LeetCode/Merge k Sorted Lists/Problem.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
4 |
5 | Merge all the linked-lists into one sorted linked-list and return it.
6 |
7 | Example 1:
8 |
9 |
10 | Input: lists = [[1,4,5],[1,3,4],[2,6]]
11 | Output: [1,1,2,3,4,4,5,6]
12 | Explanation: The linked-lists are:
13 | [
14 | 1->4->5,
15 | 1->3->4,
16 | 2->6
17 | ]
18 | merging them into one sorted list:
19 | 1->1->2->3->4->4->5->6
20 |
21 |
22 | Example 2:
23 |
24 |
25 | Input: lists = []
26 | Output: []
27 |
28 |
29 | Example 3:
30 |
31 |
32 | Input: lists = [[]]
33 | Output: []
34 |
35 |
36 | Constraints:
37 |
38 |
39 | k==lists.length
40 | 0 <= k <= 10^4
41 | 0 <= lists[i].length <= 500
42 | -10^4 <= lists[i][j] <= 10^4
43 | lists[i] is sorted in ascending order.
44 | - The sum of
lists[i].length will not exceed 10^4.
45 |
46 |
47 |
--------------------------------------------------------------------------------
/LeetCode/Spiral-Matrix-Using-Python/Python/Readme.md:
--------------------------------------------------------------------------------
1 | # Spiral Matrix
2 | The Spiral Matrix problem takes a 2-Dimensional array of N-rows and M-columns as an input, and prints the elements of this matrix in spiral order. The spiral begins at the top left corner of the input matrix, and prints the elements it encounters, while looping towards the center of this matrix, in a clockwise manner.
3 |
4 | ## How to Run
5 |
6 | 1. Make sure you have a python compiler installed on your system.
7 |
8 | 2. Clone this repository to your local machine or download the `solution.py` file.
9 |
10 | 3. Open your terminal or command prompt.
11 |
12 | 4. Navigate to the directory where the `solution.py` file is located.
13 |
14 | 5. Compile the python code using your compiler.
15 |
16 | 6. Run the program by executing the generated executable:
17 |
18 | 7. The program will execute and display the result.
19 |
20 | ## Example Usage
21 |
22 | Here's an example of how to use this program:
23 |
24 | ## Example 1:
25 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
26 |
27 | Output: [1,2,3,6,9,8,7,4,5]
28 | ```shell
29 | $ python solution.py
30 | Output:[1,2,3,6,9,8,7,4,5]
31 | ```
32 |
33 | ## screenshot
34 | 
35 |
36 | ## Customization
37 | You can easily customize the program to suit your needs. For example, you can modify the starting value of the spiral matrix, change the direction (e.g., counterclockwise), or format the output differently.
38 |
39 | ## Author
40 | This program was written by Nawin Kumar Sharma. You can reach me at nawinsharma60@gmail.com for any questions or feedback.
--------------------------------------------------------------------------------
/LeetCode/15-3Sum/python/threesum.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def threeSum(self, nums):
3 | ans = []
4 | nums.sort()
5 |
6 | for i in range(len(nums) - 2):
7 | # Skip duplicate elements
8 | if i == 0 or nums[i] != nums[i - 1]:
9 | low, high = i + 1, len(nums) - 1
10 | target = -nums[i]
11 |
12 | while low < high:
13 | if nums[low] + nums[high] == target:
14 | ans.append([nums[i], nums[low], nums[high]])
15 |
16 | # Skip duplicate elements
17 | while low < high and nums[low] == nums[low + 1]:
18 | low += 1
19 | while low < high and nums[high] == nums[high - 1]:
20 | high -= 1
21 |
22 | low += 1
23 | high -= 1
24 | elif nums[low] + nums[high] < target:
25 | low += 1
26 | else:
27 | high -= 1
28 |
29 | return ans
30 |
31 | # Test the code
32 | if __name__ == "__main__":
33 | # Input handling
34 | nums = list(map(int, input().split()))
35 |
36 | # Create an instance of the Solution class
37 | solution = Solution()
38 |
39 | # Call the threeSum function
40 | result = solution.threeSum(nums)
41 |
42 | # Print the result
43 | for triplet in result:
44 | print(triplet)
45 |
--------------------------------------------------------------------------------
/LeetCode/Concatenation-of-Array/Python/PROBLEM.md:
--------------------------------------------------------------------------------
1 | PROBLEM:
2 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
3 |
4 | HOW I SOLVED IT:
5 | Function Definition:
6 | def create_ans(nums): defines a function named create_ans that takes a list nums as input.
7 |
8 | Finding the Length:
9 | n = len(nums) calculates the length of the input list nums and assigns it to the variable n.
10 |
11 | Initializing ans List:
12 | ans = [0] * (2 * n) creates a list called ans with a length of 2n (twice the length of nums). All elements in this list are initially set to 0.
13 |
14 | Loop to Assign Values:
15 | for i in range(n): initiates a loop that will iterate n times, where n is the length of nums.
16 |
17 | Assignment of Values:
18 | ans[i] = ans[i + n] = nums[i] is a compound assignment statement that does the following:
19 | ans[i] = nums[i]: Assigns the value of nums[i] to the i-th element of ans.
20 | ans[i + n] = nums[i]: Assigns the same value to the element at index i + n in ans.
21 | This line essentially copies the value from nums[i] to both ans[i] and ans[i + n].
22 |
23 | Returning the Result:
24 | return ans returns the modified ans list.
25 |
26 | Example Usage:
27 | nums = [1, 2, 3, 4]: An example list is provided.
28 |
29 | Calling the Function:
30 | ans = create_ans(nums) calls the create_ans function with nums as an argument. The returned list is assigned to the variable ans.
31 |
32 | Printing the Result:
33 | print(ans) prints the final result.
--------------------------------------------------------------------------------
/LeetCode/Concatenation-of-Array/python/PROBLEM.md:
--------------------------------------------------------------------------------
1 | PROBLEM:
2 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
3 |
4 | HOW I SOLVED IT:
5 | Function Definition:
6 | def create_ans(nums): defines a function named create_ans that takes a list nums as input.
7 |
8 | Finding the Length:
9 | n = len(nums) calculates the length of the input list nums and assigns it to the variable n.
10 |
11 | Initializing ans List:
12 | ans = [0] * (2 * n) creates a list called ans with a length of 2n (twice the length of nums). All elements in this list are initially set to 0.
13 |
14 | Loop to Assign Values:
15 | for i in range(n): initiates a loop that will iterate n times, where n is the length of nums.
16 |
17 | Assignment of Values:
18 | ans[i] = ans[i + n] = nums[i] is a compound assignment statement that does the following:
19 | ans[i] = nums[i]: Assigns the value of nums[i] to the i-th element of ans.
20 | ans[i + n] = nums[i]: Assigns the same value to the element at index i + n in ans.
21 | This line essentially copies the value from nums[i] to both ans[i] and ans[i + n].
22 |
23 | Returning the Result:
24 | return ans returns the modified ans list.
25 |
26 | Example Usage:
27 | nums = [1, 2, 3, 4]: An example list is provided.
28 |
29 | Calling the Function:
30 | ans = create_ans(nums) calls the create_ans function with nums as an argument. The returned list is assigned to the variable ans.
31 |
32 | Printing the Result:
33 | print(ans) prints the final result.
--------------------------------------------------------------------------------
/LeetCode/Concatenation-of-Array/python/python/PROBLEM.md:
--------------------------------------------------------------------------------
1 | PROBLEM:
2 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
3 |
4 | HOW I SOLVED IT:
5 | Function Definition:
6 | def create_ans(nums): defines a function named create_ans that takes a list nums as input.
7 |
8 | Finding the Length:
9 | n = len(nums) calculates the length of the input list nums and assigns it to the variable n.
10 |
11 | Initializing ans List:
12 | ans = [0] * (2 * n) creates a list called ans with a length of 2n (twice the length of nums). All elements in this list are initially set to 0.
13 |
14 | Loop to Assign Values:
15 | for i in range(n): initiates a loop that will iterate n times, where n is the length of nums.
16 |
17 | Assignment of Values:
18 | ans[i] = ans[i + n] = nums[i] is a compound assignment statement that does the following:
19 | ans[i] = nums[i]: Assigns the value of nums[i] to the i-th element of ans.
20 | ans[i + n] = nums[i]: Assigns the same value to the element at index i + n in ans.
21 | This line essentially copies the value from nums[i] to both ans[i] and ans[i + n].
22 |
23 | Returning the Result:
24 | return ans returns the modified ans list.
25 |
26 | Example Usage:
27 | nums = [1, 2, 3, 4]: An example list is provided.
28 |
29 | Calling the Function:
30 | ans = create_ans(nums) calls the create_ans function with nums as an argument. The returned list is assigned to the variable ans.
31 |
32 | Printing the Result:
33 | print(ans) prints the final result.
--------------------------------------------------------------------------------
/.github/workflows/stale-issue-and-pr.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: Stale Issue And PR
3 |
4 | on:
5 | schedule:
6 | - cron: "0 12 * * *"
7 | workflow_dispatch:
8 | concurrency:
9 | group: environment-${{ github.ref }}
10 | cancel-in-progress: true
11 | jobs:
12 | stale:
13 | name: 🧹 Clean up stale issues and PRs
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: 🚀 Stale Issue And PR
17 | uses: actions/stale@v8
18 | with:
19 | repo-token: ${{ secrets.GITHUB_TOKEN }}
20 | days-before-stale: 30
21 | days-before-close: 7
22 | remove-stale-when-updated: true
23 | stale-issue-label: "stale"
24 | exempt-issue-labels: "no-stale,help-wanted"
25 | stale-issue-message: >
26 | There hasn't been any activity on this issue recently, and in order to prioritize active issues, it will be
27 | marked as stale. Please make sure to update to the latest version and check if that solves the issue. Let us
28 | know if that works for you by leaving a 👍 Because this issue is marked as stale, it will be closed and
29 | locked in 7 days if no further activity occurs. Thank you for your contributions!
30 | stale-pr-label: "stale"
31 | exempt-pr-labels: "no-stale"
32 | stale-pr-message: >
33 | There hasn't been any activity on this pull request recently, and in order to prioritize active work, it has
34 | been marked as stale. This PR will be closed and locked in 7 days if no further activity occurs. Thank you
35 | for your contributions!
--------------------------------------------------------------------------------
/GeeksForGeeks/Longest-Common-Subsequence/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # Longest Common Subsequences
2 |
3 | Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
4 |
5 |
Example 1:
6 |
7 |
Input:
8 | A = 6, B = 6
9 | str1 = ABCDGH
10 | str2 = AEDFHR
11 | Output: 3
12 | Explanation: LCS for input Sequences
13 | “ABCDGH” and “AEDFHR” is “ADH” of
14 | length 3.
15 |
16 |
17 |
Example 2:
18 |
19 |
Input:
20 | A = 3, B = 2
21 | str1 = ABC
22 | str2 = AC
23 | Output: 2
24 | Explanation: LCS of "ABC" and "AC" is
25 | "AC" of length 2.
26 |
27 |
Your Task:
28 | Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them.
29 |
30 |
Expected Time Complexity : O(|str1|*|str2|)
31 | Expected Auxiliary Space: O(|str1|*|str2|)
32 |
33 |
Constraints:
34 | 1<=size(str1),size(str2)<=103
35 |
36 |
--------------------------------------------------------------------------------
/LeetCode/Find Peak Element/Problem.md:
--------------------------------------------------------------------------------
1 | Medium
A peak element is an element that is strictly greater than its neighbors.
2 |
3 |
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
4 |
5 |
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
6 |
7 |
You must write an algorithm that runs in O(log n) time.
8 |
9 |
10 |
Example 1:
11 |
12 |
Input: nums = [1,2,3,1]
13 | Output: 2
14 | Explanation: 3 is a peak element and your function should return the index number 2.
15 |
16 |
Example 2:
17 |
18 |
Input: nums = [1,2,1,3,5,6,4]
19 | Output: 5
20 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | 1 <= nums.length <= 1000
27 | -231 <= nums[i] <= 231 - 1
28 | nums[i] != nums[i + 1] for all valid i.
29 |
30 |
31 |
--------------------------------------------------------------------------------
/LeetCode/150-Evaluate-Reverse-Polish-Notation/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/)
2 |
3 | You are given an array of strings tokens that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
4 |
5 | Evaluate the expression. Return an integer that represents the value of the expression.
6 |
7 | **Note** that:
8 |
9 | * The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`.
10 | * Each operand may be an integer or another expression.
11 | * The division between two integers always **truncates toward zero**.
12 | * There will not be any division by zero.
13 | * The input represents a valid arithmetic expression in a reverse polish notation.
14 | * The answer and all the intermediate calculations can be represented in a **32-bit** integer.
15 |
16 |
17 | ## Example 1:
18 |
19 | Input: tokens = ["2","1","+","3","*"]
20 | Output: 9
21 | Explanation: ((2 + 1) * 3) = 9
22 |
23 | ## Example 2:
24 |
25 | Input: tokens = ["4","13","5","/","+"]
26 | Output: 6
27 | Explanation: (4 + (13 / 5)) = 6
28 |
29 | ## Example 3:
30 |
31 | Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
32 | Output: 22
33 | Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
34 | = ((10 * (6 / (12 * -11))) + 17) + 5
35 | = ((10 * (6 / -132)) + 17) + 5
36 | = ((10 * 0) + 17) + 5
37 | = (0 + 17) + 5
38 | = 17 + 5
39 | = 22
40 |
41 |
42 | ## Constraints:
43 |
44 | 1 <= tokens.length <= 104
45 | tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
--------------------------------------------------------------------------------
/LeetCode/37-sudoku-solver/Problem.md:
--------------------------------------------------------------------------------
1 | # 37. Sudoku Solver
2 |
3 |
4 | Write a program to solve a Sudoku puzzle by filling the empty cells.
5 |
6 | A sudoku solution must satisfy all of the following rules:
7 |
8 | - Each of the digits 1-9 must occur exactly once in each row.
9 | - Each of the digits 1-9 must occur exactly once in each column.
10 | - Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
11 |
12 | The '.' character indicates empty cells.
13 |
14 |
15 | #### Example 1
16 |
17 | **Input:**
18 | ```
19 | [["5","3",".",".","7",".",".",".","."],
20 | ["6",".",".","1","9","5",".",".","."],
21 | [".","9","8",".",".",".",".","6","."],
22 | ["8",".",".",".","6",".",".",".","3"],
23 | ["4",".",".","8",".","3",".",".","1"],
24 | ["7",".",".",".","2",".",".",".","6"],
25 | [".","6",".",".",".",".","2","8","."],
26 | [".",".",".","4","1","9",".",".","5"],
27 | [".",".",".",".","8",".",".","7","9"]]
28 | ```
29 | **Output:**
30 | ```
31 | [["5","3","4","6","7","8","9","1","2"],
32 | ["6","7","2","1","9","5","3","4","8"],
33 | ["1","9","8","3","4","2","5","6","7"],
34 | ["8","5","9","7","6","1","4","2","3"],
35 | ["4","2","6","8","5","3","7","9","1"],
36 | ["7","1","3","9","2","4","8","5","6"],
37 | ["9","6","1","5","3","7","2","8","4"],
38 | ["2","8","7","4","1","9","6","3","5"],
39 | ["3","4","5","2","8","6","1","7","9"]]
40 | ```
41 |
42 | **Explanation:**
43 | The empty cells are filled with the possible numbers. There can exist many such arrangements of numbers. The above solution is one of them. Let’s see how we can fill the cells below.
44 |
--------------------------------------------------------------------------------
/LeetCode/2-add-two-numbers/Problem.md:
--------------------------------------------------------------------------------
1 | 
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
2 |
3 | You may assume the two numbers do not contain any leading zero, except the number 0 itself.
4 |
5 |
6 | Example 1:
7 |
8 |
9 | Input: l1 = [2,4,3], l2 = [5,6,4]
10 | Output: [7,0,8]
11 | Explanation: 342 + 465 = 807.
12 |
13 |
14 | Example 2:
15 |
16 |
17 | Input: l1 = [0], l2 = [0]
18 | Output: [0]
19 |
20 |
21 | Example 3:
22 |
23 |
24 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
25 | Output: [8,9,9,9,0,0,0,1]
26 |
27 |
28 |
29 | Constraints:
30 |
31 |
32 | - The number of nodes in each linked list is in the range
[1, 100].
33 | 0 <= Node.val <= 9
34 | - It is guaranteed that the list represents a number that does not have leading zeros.
35 |
36 |
--------------------------------------------------------------------------------
/LeetCode/N-Queens/python/Nqueens.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def solveNQueens(self, n):
3 | def isSafe(row, col, queens):
4 | # Check if placing a queen at (row, col) is safe from other queens
5 | for r, c in queens:
6 | if col == c or row - col == r - c or row + col == r + c:
7 | return False
8 | return True
9 |
10 | def solve(row, queens):
11 | # Base case: All queens are placed successfully
12 | if row == n:
13 | solutions.append(queens[:])
14 | return
15 |
16 | for col in range(n):
17 | if isSafe(row, col, queens):
18 | queens.append((row, col))
19 | solve(row + 1, queens)
20 | queens.pop()
21 |
22 | solutions = []
23 | queens = []
24 | solve(0, queens)
25 |
26 | # Convert solutions to the required format
27 | result = []
28 | for queens in solutions:
29 | board = [['.' for _ in range(n)] for _ in range(n)]
30 | for row, col in queens:
31 | board[row][col] = 'Q'
32 | result.append([''.join(row) for row in board])
33 |
34 | return result
35 |
36 |
37 | # Example usage:
38 | if __name__ == "__main__":
39 | n = 8 # Change 'n' to the desired board size
40 | solution = Solution()
41 | solutions = solution.solveNQueens(n)
42 |
43 | # Print the solutions
44 | for i, sol in enumerate(solutions):
45 | print(f"Solution {i + 1}:")
46 | for row in sol:
47 | print(row)
48 | print()
49 |
--------------------------------------------------------------------------------
/HackerRank/Grid_Search/problem.md:
--------------------------------------------------------------------------------
1 | Given an array of strings of digits, try to find the occurrence of a given pattern of digits. In the grid and pattern arrays, each string represents a row in the grid. For example, consider the following grid:
2 |
3 | 1234567890
4 | 0987654321
5 | 1111111111
6 | 1111111111
7 | 2222222222
8 |
9 | The pattern array is:
10 | 876543
11 | 111111
12 | 111111
13 |
14 | The pattern begins at the second row and the third column of the grid and continues in the following two rows. The pattern is said to be present in the grid. The return value should be YES or NO, depending on whether the pattern is found. In this case, return YES.
15 |
16 | Function Description:
17 | Complete the gridSearch function in the editor below. It should return YES if the pattern exists in the grid, or NO otherwise.
18 |
19 | gridSearch has the following parameter(s):
20 |
21 | string G[R]: the grid to search
22 | string P[r]: the pattern to search for
23 | Input Format
24 |
25 | The first line contains an integer , the number of test cases.
26 |
27 | Each of the test cases is represented as follows:
28 | The first line contains two space-separated integers and , the number of rows in the search grid and the length of each row string.
29 | This is followed by lines, each with a string of digits that represent the grid .
30 | The following line contains two space-separated integers, and , the number of rows in the pattern grid and the length of each pattern row string.
31 | This is followed by lines, each with a string of digits that represent the pattern grid .
32 |
33 | Returns
34 | string: either YES or NO
35 |
36 |
37 |
38 | Constraints
39 |
40 |
--------------------------------------------------------------------------------
/LeetCode/Search-Insert-Position/C++/SearchInsertPosition.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | class Solution
6 | {
7 | public:
8 | int searchInsert(vector &nums, int target)
9 | {
10 | int start = 0; // initialize start index of binary search
11 | int end = nums.size() - 1; // initialize end index of binary search
12 |
13 | while (start <= end) {
14 | // perform binary search
15 | int mid = start + (end - start) / 2; // calculate mid index
16 |
17 | if (nums[mid] == target) {
18 | // if element found at mid, return mid
19 | return mid;
20 | }
21 | else if(nums[mid] < target){
22 | // if element at mid is less than target, then target would be inserted after mid
23 | start = mid + 1;
24 | }
25 | else {
26 | // if element at mid is greater than target, then target would be inserted before mid
27 | end = mid - 1;
28 | }
29 | }
30 | // If target is not found and start is greater thsn end, it means target would be inserted at start index
31 | return start;
32 | }
33 | };
34 |
35 | int main() {
36 | Solution solution; // Create object of Solution class
37 | vector nums = {1,3,5,6}; // Example input array
38 | int target = 5; // Target element to search
39 | int result = solution.searchInsert(nums, target);
40 | cout << "The index of the target element is: " << result << endl; // Outputs the index of the target element or the index where it needs to be inserted
41 | return 0;
42 | }
--------------------------------------------------------------------------------
/LeetCode/Largest Rectangle in Histogram/C++/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | vector nextSmallerElement(vector& heights, int n) {
4 | stack s;
5 | s.push(-1);
6 | vector ans(n);
7 |
8 | for (int i = n-1; i>=0; i--) {
9 | int curr = heights[i];
10 | while(s.top() != -1 && heights[s.top()] >= curr) {
11 | s.pop();
12 | }
13 | ans[i] = s.top();
14 | s.push(i);
15 | }
16 | return ans;
17 | }
18 |
19 | vector prevSmallerElement(vector& heights, int n) {
20 | stack s;
21 | s.push(-1);
22 | vector ans(n);
23 |
24 | for (int i = 0; i = curr) {
27 | s.pop();
28 | }
29 | ans[i] = s.top();
30 | s.push(i);
31 | }
32 | return ans;
33 | }
34 |
35 |
36 | public:
37 | int largestRectangleArea(vector& heights) {
38 | int n = heights.size();
39 | vector next(n);
40 | next = nextSmallerElement(heights, n);
41 |
42 | vector prev(n);
43 | prev = prevSmallerElement(heights, n);
44 | int area = INT_MIN;
45 | for (int i = 0; i < n; i++) {
46 | int l = heights[i];
47 | if (next[i] == -1){
48 | next[i] = n;
49 | }
50 | int b = next[i] - prev[i] - 1;
51 | int newArea = l*b;
52 | area = max(area, newArea);
53 | }
54 | return area;
55 | }
56 | };
--------------------------------------------------------------------------------
/LeetCode/Reverse-Linked-List/C++/reverseLinkedList.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | // * Definition for singly-linked list.
5 | struct ListNode
6 | {
7 | int val;
8 | ListNode *next;
9 | ListNode() : val(0), next(nullptr) {}
10 | ListNode(int x) : val(x), next(nullptr) {}
11 | ListNode(int x, ListNode *next) : val(x), next(next) {}
12 | };
13 |
14 | // TC : O(N) where N is the number of nodes in the linked list, SC = O(1)
15 | class Solution
16 | {
17 | public:
18 | ListNode *reverseList(ListNode *head)
19 | {
20 | if (head == NULL || head->next == NULL)
21 | {
22 | return head;
23 | }
24 |
25 | ListNode *prev = NULL, *curr = head, *nxt;
26 |
27 | while (curr != NULL)
28 | {
29 | nxt = curr->next;
30 |
31 | curr->next = prev;
32 | prev = curr;
33 | curr = nxt;
34 | }
35 |
36 | return prev;
37 | }
38 | };
39 |
40 | int main()
41 | {
42 | Solution sol;
43 |
44 | // 1->2->3->4
45 | ListNode *head = new ListNode(1);
46 | head->next = new ListNode(2);
47 | head->next->next = new ListNode(3);
48 | head->next->next->next = new ListNode(4);
49 |
50 | cout << "original linked list: ";
51 | ListNode *temp = head;
52 | while (temp)
53 | {
54 | cout << temp->val << " ";
55 | temp = temp->next;
56 | }
57 |
58 | cout << endl;
59 |
60 | head = sol.reverseList(head);
61 | cout << "reversed linked list: ";
62 | while (head)
63 | {
64 | cout << head->val << " ";
65 | head = head->next;
66 | }
67 |
68 | return 0;
69 | }
--------------------------------------------------------------------------------
/HackerRank/Max-Min-Sum/PROBLEM.md:
--------------------------------------------------------------------------------
1 | # [Max-Min Sum](https://www.hackerrank.com/challenges/one-month-preparation-kit-mini-max-sum/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=preparation-kits&playlist_slugs%5B%5D=one-month-preparation-kit&playlist_slugs%5B%5D=one-month-week-one)
2 |
3 | Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
4 |
5 | Example
6 |
7 | The minimum sum is and the maximum sum is . The function prints
8 |
9 | 16 24
10 | Function Description
11 |
12 | Complete the miniMaxSum function in the editor below.
13 |
14 | miniMaxSum has the following parameter(s):
15 |
16 | arr: an array of integers
17 | Print
18 |
19 | Print two space-separated integers on one line: the minimum sum and the maximum sum of of elements.
20 |
21 | Input Format
22 |
23 | A single line of five space-separated integers.
24 |
25 | Constraints
26 |
27 | Output Format
28 |
29 | Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)
30 |
31 | Sample Input
32 |
33 | 1 2 3 4 5
34 | Sample Output
35 |
36 | 10 14
37 | Explanation
38 |
39 | The numbers are , , , , and . Calculate the following sums using four of the five integers:
40 |
41 | Sum everything except , the sum is .
42 | Sum everything except , the sum is .
43 | Sum everything except , the sum is .
44 | Sum everything except , the sum is .
45 | Sum everything except , the sum is .
46 |
--------------------------------------------------------------------------------
/LeetCode/Split-Array-Largest-Sum/C++/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | class Solution {
6 | public:
7 |
8 | bool isPossible(vector& nums, int k, int n, int mid){
9 | int count=0;
10 | int sum=0;
11 | for(int i=0;i=k || nums[i]>mid){
18 | return false;
19 | }
20 | sum=nums[i];
21 | }
22 | }
23 | return true;
24 |
25 | }
26 |
27 | int splitArray(vector& nums, int k) {
28 | int s=0;
29 | int n=nums.size();
30 | int sum=0;
31 | for(int i=0;i arr = {7,2,5,10,8};
61 | int k = 2;
62 |
63 | int result = solution.splitArray(arr,k);
64 |
65 | if (result)
66 | {
67 | cout<