diff --git a/dsa-problems/gfg-problems/hard/0101-0200.md b/dsa-problems/gfg-problems/hard/0101-0200.md
index 1cabbfd0e..7252944af 100644
--- a/dsa-problems/gfg-problems/hard/0101-0200.md
+++ b/dsa-problems/gfg-problems/hard/0101-0200.md
@@ -16,6 +16,12 @@ export const problems = [
"solutionLink": "/dsa-solutions/gfg-solutions/Hard/0101-0200/binary-tree-to-dll",
"problemName": "Binary Tree to DLL"
},
+ {
+ "difficulty": "Hard",
+ "gfgLink": "https://www.geeksforgeeks.org/problems/lru-cache/1",
+ "solutionLink": "/dsa-solutions/gfg-solutions/Hard/0101-0200/lru-cache",
+ "problemName": "LRU Cache"
+ },
{
"difficulty": "Hard",
"gfgLink": "https://www.geeksforgeeks.org/problems/number-of-turns-in-binary-tree/1",
diff --git a/dsa-solutions/gfg-solutions/Easy problems/square-root.md b/dsa-solutions/gfg-solutions/Easy problems/square-root.md
index 9777b7f9e..640a3c101 100644
--- a/dsa-solutions/gfg-solutions/Easy problems/square-root.md
+++ b/dsa-solutions/gfg-solutions/Easy problems/square-root.md
@@ -1,16 +1,11 @@
---
id: square-root
title: Square Root
-sidebar_label: 9 Square Root
+sidebar_label: Square-Root
tags:
- Math
- Binary Search
-- Python
-- Java
-- C++
-- JavaScript
-- TypeScript
-description: "This document provides solutions to the problem of finding the square root of a given integer using various programming languages."
+description: "This document provides solutions to the problem of finding the Square Root of an integer."
---
## Problem
@@ -43,7 +38,7 @@ You don't need to read input or print anything. The task is to complete the func
**Expected Auxiliary Space:** $O(1)$
**Constraints**
-- $1 ≤ x ≤ 10^7$
+- `1 ≤ x ≤ 10^7`
## Solution
@@ -190,11 +185,4 @@ class Solution {
The provided solutions efficiently find the floor value of the square root of a given integer `x` using binary search. This approach ensures a time complexity of $ O(log N) and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle large values of `x` up to 10^7 efficiently without relying on built-in square root functions.
**Time Complexity:** $O(log N)$
-**Auxiliary Space:** $O(1)$
-
----
-
-## References
-
-- **GeeksforGeeks Problem:** [Square root](https://www.geeksforgeeks.org/problems/square-root/0)
-- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/)
\ No newline at end of file
+**Auxiliary Space:** $O(1)$
\ No newline at end of file
diff --git a/dsa-solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md b/dsa-solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md
new file mode 100644
index 000000000..9bd92ee7f
--- /dev/null
+++ b/dsa-solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md
@@ -0,0 +1,296 @@
+---
+id: lru-cache
+title: LRU Cache
+sidebar_label: LRU Cache
+
+tags:
+- Linked List
+- DLL
+- Hash
+- Queue
+- Design Pattern
+- Data Structures
+
+description: "This is a solution to the LRU Cache problem on GeeksForGeeks."
+---
+
+## Problem Description
+Design a data structure that works like a LRU Cache. Here **cap** denotes the capacity of the cache and Q denotes the number of queries. Query can be of two types:
+- **SET x y**: sets the value of the key x with value y
+- **GET x**: gets the key of x if present else returns -1.
+
+The LRUCache class has two methods get() and set() which are defined as follows.
+- **get(key)**: returns the value of the key if it already exists in the cache otherwise returns -1.
+- **set(key, value)**: if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item.
+- In the constructor of the class the capacity of the cache should be initialized.
+
+### Examples
+
+**Example 1:**
+```
+Input:
+cap = 2
+Q = 2
+Queries = SET 1 2 GET 1
+
+Output:
+2
+
+Explanation:
+Cache Size = 2
+
+SET 1 2 GET 1
+SET 1 2 : 1 -> 2
+
+GET 1 : Print the value corresponding
+to Key 1, ie 2.
+```
+
+**Example 2:**
+```
+Input:
+cap = 2
+Q = 8
+Queries = SET 1 2 SET 2 3 SET 1 5
+SET 4 5 SET 6 7 GET 4 SET 1 2 GET 3
+
+Output:
+5 -1
+
+Explanation:
+Cache Size = 2
+SET 1 2 : 1 -> 2
+
+SET 2 3 : 1 -> 2, 2 -> 3 (the most recently
+used one is kept at the rightmost position)
+
+SET 1 5 : 2 -> 3, 1 -> 5
+
+SET 4 5 : 1 -> 5, 4 -> 5 (Cache size is 2, hence
+we delete the least recently used key-value pair)
+
+SET 6 7 : 4 -> 5, 6 -> 7
+
+GET 4 : Prints 5 (The cache now looks like
+6 -> 7, 4->5)
+
+SET 1 2 : 4 -> 5, 1 -> 2
+(Cache size is 2, hence we delete the least
+recently used key-value pair)
+
+GET 3 : No key value pair having
+key = 3. Hence, -1 is printed.
+```
+
+
+### Constraints
+- `1 ≤ Cap ≤ 10^3`
+- `1 ≤ Q ≤ 10^5`
+- `1 ≤ x,y ≤ 10^4`
+
+
+## Solution for LRU Cache
+### Approach
+#### Brute Force
+In the brute force approach, we'll use a list to maintain the order of elements and a dictionary to store key-value pairs. This solution will not meet the requirement of O(1) time complexity for both `get()` and `set()` operations but will help in understanding the mechanism.
+- **Initialization**: Use a dictionary `cache` to store the key-value pairs and a list order to store the keys in the `order` of their usage.
+- **GET Operation:**
+ - If the key exists in the cache, move the key to the end of the order list (to mark it as recently used) and return the value.
+ - If the key does not exist, return -1.
+- **SET Operation:**
+ - If the key already exists, update the value and move the key to the end of the `order` list.
+ - If the key does not exist and the cache is not full, add the key-value pair and append the key to the end of the `order` list.
+ - If the cache is full, remove the least recently used item (the first item in the `order` list), then add the new key-value pair and append the key to the end of the `order` list.
+
+
+**Implementation:**
+```python
+class LRUCache:
+ def __init__(self, capacity: int):
+ self.capacity = capacity
+ self.cache = {}
+ self.order = []
+
+ def get(self, key: int) -> int:
+ if key in self.cache:
+ self.order.remove(key)
+ self.order.append(key)
+ return self.cache[key]
+ return -1
+
+ def set(self, key: int, value: int) -> None:
+ if key in self.cache:
+ self.cache[key] = value
+ self.order.remove(key)
+ else:
+ if len(self.cache) >= self.capacity:
+ lru = self.order.pop(0)
+ del self.cache[lru]
+ self.cache[key] = value
+ self.order.append(key)
+
+# Example usage
+lru_cache = LRUCache(2)
+lru_cache.set(1, 2)
+print(lru_cache.get(1)) # Output: 2
+```
+
+#### Complexity Analysis:
+- Time Complexity:
+ - `get()`: O(n) due to list removal and append operations.
+ - `set()`: O(n) due to list removal and append operations.
+- Space Complexity:
+ - O(n) where n is the capacity of the cache.
+
+
+#### Optimized Approach
+ For an optimized solution, we can use an OrderedDict from the collections module in Python, which maintains the order of insertion and provides O(1) time complexity for both get() and set() operations.
+- **Steps**:
+ - Initialization: Use an OrderedDict to store the key-value pairs and maintain the order of insertion.
+ - GET Operation:
+ - If the key exists in the cache, move the key to the end (to mark it as recently used) and return the value.
+ - If the key does not exist, return -1.
+ - SET Operation:
+ - If the key already exists, update the value and move the key to the end.
+ - If the key does not exist and the cache is not full, add the key-value pair.
+ - If the cache is full, remove the first item (the least recently used item), then add the new key-value pair.
+
+**Implementation:**
+```python
+from collections import OrderedDict
+
+class LRUCache:
+ def __init__(self, capacity: int):
+ self.cache = OrderedDict()
+ self.capacity = capacity
+
+ def get(self, key: int) -> int:
+ if key in self.cache:
+ self.cache.move_to_end(key)
+ return self.cache[key]
+ return -1
+
+ def set(self, key: int, value: int) -> None:
+ if key in self.cache:
+ self.cache.move_to_end(key)
+ self.cache[key] = value
+ if len(self.cache) > self.capacity:
+ self.cache.popitem(last=False)
+
+# Example usage
+lru_cache = LRUCache(2)
+lru_cache.set(1, 2)
+print(lru_cache.get(1)) # Output: 2
+```
+
+**Complexity:**
+- Time Complexity: O(1) for both `get()` and `set()`.
+- Space Complexity: O(n) where n is the capacity of the cache.
+
+**Corner Cases:**
+- When the cache is empty, `get()` should return -1 for any key.
+- When inserting into a full cache, ensure the least recently used item is removed.
+- Ensure `set()` updates the value and position if the key already exists.
+- Handling of negative and zero capacity should be considered (though usually, capacity will be a positive integer).
+
+
+## Code in Different Languages
+
+
+
+
+
+
+ ```java
+ import java.util.LinkedHashMap;
+ import java.util.Map;
+
+ class LRUCache {
+ private final int capacity;
+ private final Map cache;
+
+ public LRUCache(int capacity) {
+ this.capacity = capacity;
+ this.cache = new LinkedHashMap(capacity, 0.75f, true) {
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > capacity;
+ }
+ };
+ }
+
+ public int get(int key) {
+ return cache.getOrDefault(key, -1);
+ }
+
+ public void set(int key, int value) {
+ cache.put(key, value);
+ }
+
+ public static void main(String[] args) {
+ LRUCache lruCache = new LRUCache(2);
+ lruCache.set(1, 2);
+ System.out.println(lruCache.get(1)); // Output: 2
+ }
+ }
+
+ ```
+
+
+
+
+
+
+ ```cpp
+ #include
+ #include
+ #include
+ using namespace std;
+
+ class LRUCache {
+ private:
+ int capacity;
+ list> cache;
+ unordered_map>::iterator> map;
+
+ public:
+ LRUCache(int capacity) : capacity(capacity) {}
+
+ int get(int key) {
+ if (map.find(key) == map.end()) {
+ return -1;
+ } else {
+ cache.splice(cache.begin(), cache, map[key]);
+ return map[key]->second;
+ }
+ }
+
+ void set(int key, int value) {
+ if (map.find(key) != map.end()) {
+ cache.splice(cache.begin(), cache, map[key]);
+ map[key]->second = value;
+ return;
+ }
+ if (cache.size() == capacity) {
+ int k = cache.back().first;
+ cache.pop_back();
+ map.erase(k);
+ }
+ cache.push_front({key, value});
+ map[key] = cache.begin();
+ }
+ };
+
+ int main() {
+ LRUCache lruCache(2);
+ lruCache.set(1, 2);
+ cout << lruCache.get(1) << endl; // Output: 2
+ return 0;
+ }
+ ```
+
+
+
+
+## References
+
+- **GeekForGeeks Problem**: [LRU Cache](https://www.geeksforgeeks.org/problems/lru-cache/1)
\ No newline at end of file
diff --git a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md
index fb5a1dfcc..4eacd7aa6 100644
--- a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md
+++ b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md
@@ -1,141 +1,188 @@
---
-id: sort-array-by-parity
+id: Sort-Array-By-Parity
title: Sort Array By Parity
-sidebar_label: 0905 - Sort Array By Parity
-tags:
- - easy
- - Arrays
- - Algorithms
+sidebar_label: Sort Array By Parity
+tags:
+ - Arrays
+ - Sorting
---
## Problem Description
-Given an integer array `nums`, move all the even integers to the beginning of the array followed by all the odd integers.
+| Problem Statement | Solution Link | LeetCode Profile |
+| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
+| [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/description/) | [Sort Array By Parity Solution on LeetCode](https://leetcode.com/problems/sort-array-by-parity/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) |
-Return any array that satisfies this condition.
+## Problem Description
-## Examples
+Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
-**Example 1:**
+Return any array that satisfies this condition.
-```
-Input: nums = [3,1,2,4]
-Output: [2,4,3,1]
-Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
-```
+### Example 1:
-**Example 2:**
+**Input:** `nums = [3, 1, 2, 4]`
+**Output:** `[2, 4, 3, 1]`
+**Explanation:** The outputs `[4, 2, 3, 1]`, `[2, 4, 1, 3]`, and `[4, 2, 1, 3]` would also be accepted.
-```
-Input: nums = [0]
-Output: [0]
-```
+### Example 2:
+
+**Input:** `nums = [0]`
+**Output:** `[0]`
## Constraints
-```
-1 <= nums.length <= 5000
-0 <= nums[i] <= 5000
-```
+- `1 <= nums.length <= 5000`
+- `0 <= nums[i] <= 5000`
+
+## Approach
+
+1. **Identify even and odd integers**: Iterate through the array and separate the even and odd integers.
+2. **Rearrange the array**: Place all even integers at the beginning of the array followed by the odd integers.
## Solution
### Python
```python
-class Solution:
- def sortArrayByParity(self, nums):
- return [x for x in nums if x % 2 == 0] + [x for x in nums if x % 2 != 0]
-
-# Example usage:
-solution = Solution()
-print(solution.sortArrayByParity([3,1,2,4])) # Output: [2,4,3,1]
+def sortArrayByParity(nums):
+ even = [x for x in nums if x % 2 == 0]
+ odd = [x for x in nums if x % 2 != 0]
+ return even + odd
+
+# Example usage
+nums = [3, 1, 2, 4]
+print(sortArrayByParity(nums)) # Output: [2, 4, 3, 1]
```
-### C++
+### Java
-```cpp
-#include
-#include
+```java
+import java.util.*;
-class Solution {
-public:
- std::vector sortArrayByParity(std::vector& nums) {
- std::vector result;
+public class EvenOddArray {
+ public static int[] sortArrayByParity(int[] nums) {
+ List even = new ArrayList<>();
+ List odd = new ArrayList<>();
+
for (int num : nums) {
if (num % 2 == 0) {
- result.push_back(num);
+ even.add(num);
+ } else {
+ odd.add(num);
}
}
- for (int num : nums) {
- if (num % 2 != 0) {
- result.push_back(num);
- }
+
+ even.addAll(odd);
+ return even.stream().mapToInt(i -> i).toArray();
+ }
+
+ public static void main(String[] args) {
+ int[] nums = {3, 1, 2, 4};
+ System.out.println(Arrays.toString(sortArrayByParity(nums))); // Output: [2, 4, 3, 1]
+ }
+}
+```
+
+### C++
+
+```cpp
+#include
+#include
+
+std::vector sortArrayByParity(std::vector& nums) {
+ std::vector even, odd;
+ for (int num : nums) {
+ if (num % 2 == 0) {
+ even.push_back(num);
+ } else {
+ odd.push_back(num);
}
- return result;
}
-};
+ even.insert(even.end(), odd.begin(), odd.end());
+ return even;
+}
-// Example usage:
int main() {
- Solution solution;
std::vector nums = {3, 1, 2, 4};
- std::vector result = solution.sortArrayByParity(nums); // Output: [2, 4, 3, 1]
- return 0;
+ std::vector result = sortArrayByParity(nums);
+ for (int num : result) {
+ std::cout << num << " ";
+ }
+ // Output: 2 4 3 1
}
```
-### Java
-
-```java
-import java.util.ArrayList;
-import java.util.List;
-
-class Solution {
- public int[] sortArrayByParity(int[] nums) {
- List result = new ArrayList<>();
- for (int num : nums) {
- if (num % 2 == 0) {
- result.add(num);
- }
- }
- for (int num : nums) {
- if (num % 2 != 0) {
- result.add(num);
- }
+### C
+
+```c
+#include
+#include
+
+void sortArrayByParity(int* nums, int numsSize, int* returnSize) {
+ int* result = (int*)malloc(numsSize * sizeof(int));
+ int evenIndex = 0, oddIndex = numsSize - 1;
+
+ for (int i = 0; i < numsSize; ++i) {
+ if (nums[i] % 2 == 0) {
+ result[evenIndex++] = nums[i];
+ } else {
+ result[oddIndex--] = nums[i];
}
- return result.stream().mapToInt(i -> i).toArray();
}
+ *returnSize = numsSize;
+ for (int i = 0; i < numsSize; ++i) {
+ nums[i] = result[i];
+ }
+ free(result);
+}
- public static void main(String[] args) {
- Solution solution = new Solution();
- int[] nums = {3, 1, 2, 4};
- int[] result = solution.sortArrayByParity(nums); // Output: [2, 4, 3, 1]
- for (int num : result) {
- System.out.print(num + " ");
- }
+int main() {
+ int nums[] = {3, 1, 2, 4};
+ int numsSize = sizeof(nums) / sizeof(nums[0]);
+ int returnSize;
+ sortArrayByParity(nums, numsSize, &returnSize);
+
+ for (int i = 0; i < numsSize; ++i) {
+ printf("%d ", nums[i]);
}
+ // Output: 2 4 3 1
+ return 0;
}
```
### JavaScript
```javascript
-var sortArrayByParity = function (nums) {
- let result = [];
- for (let num of nums) {
- if (num % 2 === 0) {
- result.push(num);
- }
- }
- for (let num of nums) {
- if (num % 2 !== 0) {
- result.push(num);
+function sortArrayByParity(nums) {
+ let even = [];
+ let odd = [];
+
+ for (let num of nums) {
+ if (num % 2 === 0) {
+ even.push(num);
+ } else {
+ odd.push(num);
+ }
}
- }
- return result;
-};
+
+ return [...even, ...odd];
+}
-// Example usage:
-console.log(sortArrayByParity([3, 1, 2, 4])); // Output: [2, 4, 3, 1]
+// Example usage
+let nums = [3, 1, 2, 4];
+console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1]
```
+
+## Step-by-Step Algorithm
+
+1. Initialize two empty lists/arrays: one for even integers and one for odd integers.
+2. Iterate through the given array:
+ - If the current integer is even, add it to the even list/array.
+ - If the current integer is odd, add it to the odd list/array.
+3. Concatenate the even list/array with the odd list/array.
+4. Return the concatenated list/array.
+
+## Conclusion
+
+This problem can be solved efficiently by iterating through the array once and separating the integers into even and odd lists/arrays. The time complexity is O(n), where n is the length of the array, making this approach optimal for the given constraints.
\ No newline at end of file