From 6af3ad5cd5e96efc6ed63b5c5d72d11390cc3d41 Mon Sep 17 00:00:00 2001 From: KapuluruBhuvaneswariVspdbct Date: Fri, 11 Oct 2024 00:29:33 +0530 Subject: [PATCH 1/5] created stack --- src/pages/Quizes/quiz.css | 0 src/pages/Quizes/stack.tsx | 280 +++++++++++++++++++++++++++++++++++++ 2 files changed, 280 insertions(+) create mode 100644 src/pages/Quizes/quiz.css create mode 100644 src/pages/Quizes/stack.tsx diff --git a/src/pages/Quizes/quiz.css b/src/pages/Quizes/quiz.css new file mode 100644 index 000000000..e69de29bb diff --git a/src/pages/Quizes/stack.tsx b/src/pages/Quizes/stack.tsx new file mode 100644 index 000000000..c7973806d --- /dev/null +++ b/src/pages/Quizes/stack.tsx @@ -0,0 +1,280 @@ +import React, { useState } from "react"; +import Layout from "@theme/Layout"; + +const StackQuiz: React.FC = () => { + const questions = [ + // Easy Questions + { + question: ( + <> + Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing. +
+            {`void fun(int n)
+{
+    Stack S;  // Say it creates an empty stack S
+    while (n > 0)
+    {
+      push(&S, n%2);
+      n = n/2;
+    }
+
+    while (!isEmpty(&S))
+      printf("%d ", pop(&S));
+}`}
+          
+ What does the above function do in general? + + ), + options: [ + "A) Prints binary representation of n in reverse order", + "B) Prints binary representation of n", + "C) Prints the value of Logn", + "D) Prints the value of Logn in reverse order", + ], + answer: "A) Prints binary representation of n in reverse order", + }, + { + question: ( + <> + Consider the following pseudocode that uses a stack: +
+            {`declare a stack of characters
+while (there are more characters in the word to read)
+{
+    read a character
+    push the character on the stack
+}
+while (the stack is not empty)
+{
+    pop a character off the stack
+    write the character to the screen
+}`}
+          
+ What is output for input "geeksquiz"? + + ), + options: [ + "A) geeksquizgeeksquiz", + "B) ziuqskeeg", + "C) geeksquiz", + "D) ziuqskeegziuqskeeg", + ], + answer: "B) ziuqskeeg", + }, + { + question: ( + <> + Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: +
+            {`declare a character stack 
+while (more input is available)
+{
+    read a character
+    if (the character is a '(' ) 
+        push it on the stack
+    else if (the character is a ')' and the stack is not empty)
+        pop a character off the stack
+    else
+        print "unbalanced" and exit
+}
+print "balanced"`}
+          
+ Which of these unbalanced sequences does the above code think is balanced? + + ), + options: [ + "A) ((())", + "B) ())(()", + "C) (()())", + "D) (()))()", + ], + answer: "D) (()))()", + }, + // Average Questions + { + question: ( + <> + The following postfix expression with single digit operands is evaluated using a stack: +
+            {`8 2 3 ^ / 2 3 * + 5 1 * -`}
+          
+ The top two elements of the stack after the first * is evaluated are: + + ), + options: [ + "A) 6, 1", + "B) 5, 7", + "C) 3, 2", + "D) 1, 5", + ], + answer: "A) 6, 1", + }, + { + question: ( + <> + A single array A[1..MAXSIZE] is used to implement two stacks. The two stacks grow from opposite ends of the array. If the space is to be used efficiently, the condition for “stack full” is: + + ), + options: [ + "A) (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)", + "B) top1 + top2 + 1 = MAXSIZE", + "C) (top1= MAXSIZE/2) or (top2 = MAXSIZE)", + "D) top1= top2 -1", + ], + answer: "B) top1 + top2 + 1 = MAXSIZE", + }, + { + question: ( + <> + Assume that the operators +, -, × are left associative and ^ is right associative. The order of precedence (from highest to lowest) is ^, x , +, -. The postfix expression corresponding to the infix expression a + b × c - d ^ e ^ f is + + ), + options: [ + "A) abc × + def ^ ^ -", + "B) abc × + de ^ f ^ -", + "C) ab + c × d - e ^ f ^", + "D) - + a × bc ^ ^ def", + ], + answer: "A) abc × + def ^ ^ -", + }, + // Difficult Questions + { + question: ( + <> + The result evaluating the postfix expression 10 5 + 60 6 / * 8 – is + + ), + options: [ + "A) 284", + "B) 213", + "C) 142", + "D) 71", + ], + answer: "C) 142", // Removed answer + }, + { + question: ( + <> + A function f defined on stacks of integers satisfies the following properties. f(∅) = 0 and f(push(S, i)) = max(f(S), 0) + i for all stacks S and integers i. + If a stack S contains the integers 2, -3, 2, -1, 2 in order from bottom to top, what is f(S)? + + ), + options: [ + "A) 6", + "B) 4", + "C) 3", + "D) 2", + ], + answer: "A) 6", + }, + { + question: ( + <> + A priority queue Q is used to implement a stack S that stores characters. PUSH(C) is implemented as INSERT(Q, C, K) where K is an appropriate integer key chosen by the implementation. For a sequence of operations, the keys chosen are in + + ), + options: [ + "A) Non-increasing order", + "B) Non-decreasing order", + "C) strictly increasing order", + "D) strictly decreasing order", + ], + answer: "C) strictly increasing order", + }, + { + question: ( + <> + If the sequence of operations - push (1), push (2), pop, push (1), push (2), pop, pop, pop, push (2), pop are performed on a stack, the sequence of popped out values + + ), + options: [ + "A) 2,2,1,1,2", + "B) 2,2,1,2,2", + "C) 2,1,2,2,1", + "D) 2,1,2,2,2", + ], + answer: "C) 2,1,2,2,1", + }, + ]; + + const [currentQuestion, setCurrentQuestion] = useState(0); + const [score, setScore] = useState(0); + const [showResult, setShowResult] = useState(false); + const [selectedOption, setSelectedOption] = useState(null); + + const handleAnswer = (selected: string) => { + setSelectedOption(selected); + if (selected === questions[currentQuestion].answer) { + setScore(score + 1); + } + }; + + const nextQuestion = () => { + if (currentQuestion < questions.length - 1) { + setCurrentQuestion(currentQuestion + 1); + setSelectedOption(null); // Reset selected option for the next question + } else { + setShowResult(true); + } + }; + + return ( + +
+

Quiz on Stacks

+ {showResult ? ( +
+

Your Score: {score} 🎉

+

+ {score <= 5 ? "Better luck next time!" : score <= 8 ? "Good job!" : "Excellent work!"} +

+
+ ) : ( +
+

{`Q${currentQuestion + 1}: `}{questions[currentQuestion].question}

+
+ {questions[currentQuestion].options.map((option) => ( + + ))} +
+ {selectedOption && ( + + )} +
+ )} +
+
+ ); +}; + +export default StackQuiz; From aba83d48417e1f7dcc3e2d3c418cac416bf122ad Mon Sep 17 00:00:00 2001 From: KapuluruBhuvaneswariVspdbct Date: Mon, 14 Oct 2024 19:50:16 +0530 Subject: [PATCH 2/5] solved #705 --- .../greedy-leetcode-solutions.md | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 docs/leetcode Solutions/greedy-leetcode-solutions.md diff --git a/docs/leetcode Solutions/greedy-leetcode-solutions.md b/docs/leetcode Solutions/greedy-leetcode-solutions.md new file mode 100644 index 000000000..b46a9a83a --- /dev/null +++ b/docs/leetcode Solutions/greedy-leetcode-solutions.md @@ -0,0 +1,183 @@ +--- +id: greedy-leetcode-solutions-1-to-10 +sidebar_position: 3 +title: greedy LeetCode Solutions 1-10 +sidebar_label: greedy LeetCode Solutions 1-10 +description: "This document contains solutions to LeetCode DSA problems 1-10 containing multiple algorithms and data structures." +tags: [leetcode, algorithms, problem-solving, DSA, data structure] +--- + +# Greedy-LeetCode Solutions 1-10 + +## Questions +1. [The Two Sneaky Numbers of Digitville](#1-the-two-sneaky-numbers-of-digitville) +2. [Design Neighbor Sum Service](#2-design-neighbor-sum-service) +3. [Find the Number of Winning Players](#3-find-the-number-of-winning-players) +4. [Count Pairs That Form a Complete Day I](#4-count-pairs-that-form-a-complete-day-i) +5. [Remove Element](#5-remove-element) +6. [Remove Duplicates from Sorted Array](#6-remove-duplicates-from-sorted-array) +7. [Merge Two Sorted Lists](#7-merge-two-sorted-lists) +8. [Generate Parentheses](#8-generate-parentheses) +9. [Merge k Sorted Lists](#9-merge-k-sorted-lists) +10. [Swap Nodes in Pairs](#10-swap-nodes-in-pairs) + +--- +## 1. The Two Sneaky Numbers of Digitville +**Description:** In Digitville, there was a list `nums` containing integers from `0` to `n-1`. Two numbers appeared an additional time, making the list longer than usual. Return an array of the two sneaky numbers that appear twice. + +**Solution:** Use a hash map to count the occurrences of each number. If a number appears more than once, add it to the result. + +```cpp +class Solution { +public: + vector getSneakyNumbers(vector& nums) { + unordered_map count; + vector result; + + for (int num : nums) { + count[num]++; + } + + for (auto& pair : count) { + if (pair.second > 1) { + result.push_back(pair.first); + } + } + + return result; + } +}; +``` + +--- + +## 2. Design Neighbor Sum Service +**Description:** You are given a n x n 2D array `grid` containing distinct elements in the range \([0, n^2 - 1]\). Implement the `NeighborSum` class with methods to find adjacent and diagonal sums around a specific value in the grid. + +**Solution:** Traverse the grid to locate the specific value, then calculate the sums of adjacent and diagonal elements based on the position of that value. + +```cpp +class NeighborSum { +private: + vector> grid; + int n; + +public: + NeighborSum(vector>& grid) : grid(grid), n(grid.size()) {} + + int adjacentSum(int value) { + int sum = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == value) { + if (i > 0) sum += grid[i - 1][j]; // top + if (i < n - 1) sum += grid[i + 1][j]; // bottom + if (j > 0) sum += grid[i][j - 1]; // left + if (j < n - 1) sum += grid[i][j + 1]; // right + } + } + } + return sum; + } + + int diagonalSum(int value) { + int sum = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == value) { + if (i > 0 && j > 0) sum += grid[i - 1][j - 1]; // top-left + if (i > 0 && j < n - 1) sum += grid[i - 1][j + 1]; // top-right + if (i < n - 1 && j > 0) sum += grid[i + 1][j - 1]; // bottom-left + if (i < n - 1 && j < n - 1) sum += grid[i + 1][j + 1]; // bottom-right + } + } + } + return sum; + } +}; +``` + +--- + +## 3. Find the Number of Winning Players +**Description:** Given the number of players `n` and a 2D array `pick` where `pick[i] = [xi, yi]` represents that player `xi` picked a ball of color `yi`. A player wins if they pick more than `i + 1` balls of the same color. Return the number of players who win. + +**Solution:** Use a vector of hash maps to count the occurrences of each color for each player and determine the winners based on the conditions specified. + +```cpp +class Solution { +public: + int winningPlayerCount(int n, vector>& pick) { + vector> color_count(n); + int winners = 0; + + for (auto& p : pick) { + color_count[p[0]][p[1]]++; + } + + for (int i = 0; i < n; i++) { + for (auto& pair : color_count[i]) { + if (pair.second > i + 1) { + winners++; + break; + } + } + } + + return winners; + } +}; +``` + +--- + +## 4. Count Pairs That Form a Complete Day I +**Description:** Given an integer array `hours` representing times in hours, return the number of pairs \((i, j)\) where \(i < j\) and `hours[i] + hours[j]` forms a complete day (i.e., a multiple of 24 hours). + +**Solution:** Use a hash map to count the occurrences of hour remainders and find complementary pairs that sum to a multiple of 24. + +```cpp +class Solution { +public: + int countCompleteDayPairs(vector& hours) { + unordered_map mod_count; + int pairs = 0; + + for (int hour : hours) { + int mod = hour % 24; + int complement = (24 - mod) % 24; + pairs += mod_count[complement]; + mod_count[mod]++; + } + + return pairs; + } +}; +``` + +--- + +## 5. Remove Element +**Description:** Given an array `nums` and a value `val`, remove all instances of `val` in-place and return the new length of the array. + +**Solution:** Use a two-pointer technique to keep track of non-target elements and overwrite the elements in the original array. + +```cpp +class Solution { +public: + int removeElement(vector& nums, int val) { + int new_index = 0; + + for (int num : nums) { + if (num != val) { + nums[new_index] = num; + new_index++; + } + } + + return new_index; + } +}; +``` + +--- From 4ba8a45d953aaf3348c500be3e8c3761e38b4c04 Mon Sep 17 00:00:00 2001 From: Bhuvaneswari Kapuluru <165504668+KapuluruBhuvaneswariVspdbct@users.noreply.github.com> Date: Mon, 14 Oct 2024 20:27:32 +0530 Subject: [PATCH 3/5] Delete src/pages/Quizes/stack.tsx --- src/pages/Quizes/stack.tsx | 284 ------------------------------------- 1 file changed, 284 deletions(-) delete mode 100644 src/pages/Quizes/stack.tsx diff --git a/src/pages/Quizes/stack.tsx b/src/pages/Quizes/stack.tsx deleted file mode 100644 index 93aa815de..000000000 --- a/src/pages/Quizes/stack.tsx +++ /dev/null @@ -1,284 +0,0 @@ -import React, { useState } from "react"; -import Layout from "@theme/Layout"; - -const StackQuiz: React.FC = () => { - const questions = [ - // Easy Questions - { - question: ( - <> - Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing. -
-            {`void fun(int n)
-{
-    Stack S;  // Say it creates an empty stack S
-    while (n > 0)
-    {
-      push(&S, n%2);
-      n = n/2;
-    }
-
-    while (!isEmpty(&S))
-      printf("%d ", pop(&S));
-}`}
-          
- What does the above function do in general? - - ), - options: [ - "A) Prints binary representation of n in reverse order", - "B) Prints binary representation of n", - "C) Prints the value of Logn", - "D) Prints the value of Logn in reverse order", - ], - answer: "A) Prints binary representation of n in reverse order", - }, - { - question: ( - <> - Consider the following pseudocode that uses a stack: -
-            {`declare a stack of characters
-while (there are more characters in the word to read)
-{
-    read a character
-    push the character on the stack
-}
-while (the stack is not empty)
-{
-    pop a character off the stack
-    write the character to the screen
-}`}
-          
- What is output for input "geeksquiz"? - - ), - options: [ - "A) geeksquizgeeksquiz", - "B) ziuqskeeg", - "C) geeksquiz", - "D) ziuqskeegziuqskeeg", - ], - answer: "B) ziuqskeeg", - }, - { - question: ( - <> - Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: -
-            {`declare a character stack 
-while (more input is available)
-{
-    read a character
-    if (the character is a '(' ) 
-        push it on the stack
-    else if (the character is a ')' and the stack is not empty)
-        pop a character off the stack
-    else
-        print "unbalanced" and exit
-}
-print "balanced"`}
-          
- Which of these unbalanced sequences does the above code think is balanced? - - ), - options: [ - "A) ((())", - "B) ())(()", - "C) (()())", - "D) (()))()", - ], - answer: "D) (()))()", - }, - // Average Questions - { - question: ( - <> - The following postfix expression with single digit operands is evaluated using a stack: -
-            {`8 2 3 ^ / 2 3 * + 5 1 * -`}
-          
- The top two elements of the stack after the first * is evaluated are: - - ), - options: [ - "A) 6, 1", - "B) 5, 7", - "C) 3, 2", - "D) 1, 5", - ], - answer: "A) 6, 1", - }, - { - question: ( - <> - A single array A[1..MAXSIZE] is used to implement two stacks. The two stacks grow from opposite ends of the array. If the space is to be used efficiently, the condition for “stack full” is: - - ), - options: [ - "A) (top1 = MAXSIZE/2) and (top2 = MAXSIZE/2+1)", - "B) top1 + top2 + 1 = MAXSIZE", - "C) (top1= MAXSIZE/2) or (top2 = MAXSIZE)", - "D) top1= top2 -1", - ], - answer: "B) top1 + top2 + 1 = MAXSIZE", - }, - { - question: ( - <> - Assume that the operators +, -, × are left associative and ^ is right associative. The order of precedence (from highest to lowest) is ^, x , +, -. The postfix expression corresponding to the infix expression a + b × c - d ^ e ^ f is - - ), - options: [ - "A) abc × + def ^ ^ -", - "B) abc × + de ^ f ^ -", - "C) ab + c × d - e ^ f ^", - "D) - + a × bc ^ ^ def", - ], - answer: "A) abc × + def ^ ^ -", - }, - // Difficult Questions - { - question: ( - <> - The result evaluating the postfix expression 10 5 + 60 6 / * 8 – is - - ), - options: [ - "A) 284", - "B) 213", - "C) 142", - "D) 71", - ], - answer: "C) 142", // Removed answer - }, - { - question: ( - <> - A function f defined on stacks of integers satisfies the following properties. f(∅) = 0 and f(push(S, i)) = max(f(S), 0) + i for all stacks S and integers i. - If a stack S contains the integers 2, -3, 2, -1, 2 in order from bottom to top, what is f(S)? - - ), - options: [ - "A) 6", - "B) 4", - "C) 3", - "D) 2", - ], - answer: "A) 6", - }, - { - question: ( - <> - A priority queue Q is used to implement a stack S that stores characters. PUSH(C) is implemented as INSERT(Q, C, K) where K is an appropriate integer key chosen by the implementation. For a sequence of operations, the keys chosen are in - - ), - options: [ - "A) Non-increasing order", - "B) Non-decreasing order", - "C) strictly increasing order", - "D) strictly decreasing order", - ], - answer: "C) strictly increasing order", - }, - { - question: ( - <> - If the sequence of operations - push (1), push (2), pop, push (1), push (2), pop, pop, pop, push (2), pop are performed on a stack, the sequence of popped out values - - ), - options: [ - "A) 2,2,1,1,2", - "B) 2,2,1,2,2", - "C) 2,1,2,2,1", - "D) 2,1,2,2,2", - ], - answer: "C) 2,1,2,2,1", - }, - ]; - - const [currentQuestion, setCurrentQuestion] = useState(0); - const [score, setScore] = useState(0); - const [showResult, setShowResult] = useState(false); - const [selectedOption, setSelectedOption] = useState(null); - - const handleAnswer = (selected: string) => { - setSelectedOption(selected); - if (selected === questions[currentQuestion].answer) { - setScore(score + 1); - } - }; - - const nextQuestion = () => { - if (currentQuestion < questions.length - 1) { - setCurrentQuestion(currentQuestion + 1); - setSelectedOption(null); // Reset selected option for the next question - } else { - setShowResult(true); - } - }; - - return ( - -
-

Quiz on Stacks

- {showResult ? ( -
-

Your Score: {score} 🎉

-

- {score <= 5 ? "Better luck next time!" : score <= 8 ? "Good job!" : "Excellent work!"} -

-
- ) : ( -
-

{`Q${currentQuestion + 1}: `}{questions[currentQuestion].question}

-
- {questions[currentQuestion].options.map((option) => ( - - ))} -
- {selectedOption && ( - - )} -
- )} -
-
- ); -}; - - -export default StackQuiz; - -export default StackQuiz; - From 049abf76276eaa9085d204fdd824780d95712ad7 Mon Sep 17 00:00:00 2001 From: Bhuvaneswari Kapuluru <165504668+KapuluruBhuvaneswariVspdbct@users.noreply.github.com> Date: Mon, 14 Oct 2024 20:27:51 +0530 Subject: [PATCH 4/5] Delete src/pages/Quizes/quiz.css --- src/pages/Quizes/quiz.css | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/pages/Quizes/quiz.css diff --git a/src/pages/Quizes/quiz.css b/src/pages/Quizes/quiz.css deleted file mode 100644 index e69de29bb..000000000 From 881d1efb40fc2f134f87bb1aff0cbe510c9fddbd Mon Sep 17 00:00:00 2001 From: Bhuvaneswari Kapuluru <165504668+KapuluruBhuvaneswariVspdbct@users.noreply.github.com> Date: Sun, 20 Oct 2024 20:32:35 +0530 Subject: [PATCH 5/5] Update greedy-leetcode-solutions.md --- docs/leetcode Solutions/greedy-leetcode-solutions.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/leetcode Solutions/greedy-leetcode-solutions.md b/docs/leetcode Solutions/greedy-leetcode-solutions.md index b3243e8ce..d1c823345 100644 --- a/docs/leetcode Solutions/greedy-leetcode-solutions.md +++ b/docs/leetcode Solutions/greedy-leetcode-solutions.md @@ -7,11 +7,10 @@ description: "This document contains solutions to LeetCode DSA problems 1-10 con tags: [leetcode, algorithms, problem-solving, DSA, data structure] --- - -# Greedy-LeetCode Solutions 1-10 -======= + + # Greedy-LeetCode Solutions 1-5 - + ## Questions 1. [The Two Sneaky Numbers of Digitville](#1-the-two-sneaky-numbers-of-digitville) @@ -19,14 +18,13 @@ tags: [leetcode, algorithms, problem-solving, DSA, data structure] 3. [Find the Number of Winning Players](#3-find-the-number-of-winning-players) 4. [Count Pairs That Form a Complete Day I](#4-count-pairs-that-form-a-complete-day-i) 5. [Remove Element](#5-remove-element) - + 6. [Remove Duplicates from Sorted Array](#6-remove-duplicates-from-sorted-array) 7. [Merge Two Sorted Lists](#7-merge-two-sorted-lists) 8. [Generate Parentheses](#8-generate-parentheses) 9. [Merge k Sorted Lists](#9-merge-k-sorted-lists) 10. [Swap Nodes in Pairs](#10-swap-nodes-in-pairs) -======= - + --- ## 1. The Two Sneaky Numbers of Digitville