Skip to content

Commit e4746b5

Browse files
authored
Merge pull request #536 from MuraliDharan7/add-gfgsol-problems
Added Easy problem solution GFG
2 parents f74688b + 164630f commit e4746b5

12 files changed

+1430
-10
lines changed

dsa-problems/gfg-problems/easy/problems.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,61 +14,61 @@ export const problems = [
1414
"problemName": "1. Reverse-a-linked-list",
1515
"difficulty": "easy",
1616
"leetCodeLink": "https://www.geeksforgeeks.org/problems/reverse-a-linked-list/0",
17-
"solutionLink": "#"
17+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Reverse-a-linked-list"
1818
},
1919
{
2020
"problemName": "2. Reverse-a-doubly-linked-list",
2121
"difficulty": "easy",
2222
"leetCodeLink": "https://www.geeksforgeeks.org/problems/reverse-a-doubly-linked-list/0",
23-
"solutionLink": "#"
23+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Reverse-a-doubly-linked-list"
2424
},
2525
{
2626
"problemName": "3. Delete-without-head-pointer",
2727
"difficulty": "easy",
2828
"leetCodeLink": "https://www.geeksforgeeks.org/problems/delete-without-head-pointer/0",
29-
"solutionLink": "#"
29+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Delete-without-head-pointer"
3030
},
3131
{
3232
"problemName": "4. Check-for-balanced-tree",
3333
"difficulty": "easy",
3434
"leetCodeLink": "https://www.geeksforgeeks.org/problems/check-for-balanced-tree/0",
35-
"solutionLink": "#"
35+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Check-for-balanced-tree"
3636
},
3737
{
3838
"problemName": "5. Delete-middle-of-linked-list",
3939
"difficulty": "easy",
4040
"leetCodeLink": "https://www.geeksforgeeks.org/problems/delete-middle-of-linked-list/0",
41-
"solutionLink": "#"
41+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Delete-middle-of-linked-list"
4242
},
4343
{
4444
"problemName": "6. Intersection-of-two-sorted-linked-lists",
4545
"difficulty": "easy",
4646
"leetCodeLink": "https://www.geeksforgeeks.org/problems/intersection-of-two-sorted-linked-lists/0",
47-
"solutionLink": "#"
47+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Intersection-of-two-sorted-linked-lists"
4848
},
4949
{
5050
"problemName": "7. DFS-traversal-of-graph",
5151
"difficulty": "easy",
5252
"leetCodeLink": "https://www.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/0",
53-
"solutionLink": "#"
53+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/DFS-traversal-of-graph"
5454
},
5555
{
5656
"problemName": "8. BFS-traversal-of-graph",
5757
"difficulty": "easy",
5858
"leetCodeLink": "https://www.geeksforgeeks.org/problems/bfs-traversal-of-graph/0",
59-
"solutionLink": "#"
59+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/BFS-traversal-of-graph"
6060
},
6161
{
6262
"problemName": "9. Square-root",
6363
"difficulty": "easy",
6464
"leetCodeLink": "https://www.geeksforgeeks.org/problems/square-root/0",
65-
"solutionLink": "#"
65+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Square-root"
6666
},
6767
{
6868
"problemName": "10. Implement-two-stacks-in-an-array",
6969
"difficulty": "easy",
7070
"leetCodeLink": "https://www.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/0",
71-
"solutionLink": "#"
71+
"solutionLink": "/dsa-solutions/gfg-solutions/problems/Implement-two-stacks-in-an-array"
7272
}
7373
]
7474

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
id: BFS-traversal-of-graph
3+
title: BFS Traversal of Graph (Geeks for Geeks)
4+
sidebar_label: BFS Traversal of Graph
5+
tags:
6+
- Intermediate
7+
- Graph
8+
- Breadth-First Search
9+
- Geeks for Geeks
10+
- CPP
11+
- Python
12+
- DSA
13+
description: "This is a solution to the BFS Traversal of Graph problem on Geeks for Geeks."
14+
---
15+
16+
## Problem Description
17+
18+
Given a graph, perform Breadth-First Search (BFS) traversal starting from a given source vertex.
19+
20+
## Examples
21+
22+
**Example:**
23+
24+
Consider the following graph:
25+
26+
```
27+
1
28+
/ \
29+
2 3
30+
/ \
31+
4 5
32+
```
33+
34+
**Output:** 1 2 3 4 5
35+
36+
## Your Task
37+
38+
Your task is to complete the function `bfs()`, which takes the graph, the number of vertices, and the source vertex as its arguments and prints the BFS traversal of the graph starting from the source vertex.
39+
40+
Expected Time Complexity: $O(V + E)$, where V is the number of vertices and E is the number of edges in the graph.
41+
Expected Auxiliary Space: $O(V)$.
42+
43+
## Constraints
44+
45+
- $1 <= number of vertices <= 10^3$
46+
- $0 <= value of vertices <= 10^3$
47+
48+
## Problem Explanation
49+
50+
Here's the step-by-step breakdown of the BFS traversal process:
51+
52+
1. **Initialize visited array**: Create a visited array to keep track of visited vertices.
53+
2. **Initialize queue**: Create a queue to store vertices to be visited next.
54+
3. **Perform BFS**: Start BFS traversal from the source vertex.
55+
4. **Enqueue source**: Enqueue the source vertex into the queue and mark it as visited.
56+
5. **Process vertices**: While the queue is not empty, dequeue a vertex, print it, and enqueue its unvisited adjacent vertices.
57+
58+
### Code Implementation
59+
60+
<Tabs>
61+
<TabItem value="Python" label="Python" default>
62+
<SolutionAuthor name="@ngmuraqrdd"/>
63+
```python
64+
from collections import deque
65+
66+
def bfs(graph, v, source):
67+
visited = [False] * v
68+
queue = deque([source])
69+
visited[source] = True
70+
71+
while queue:
72+
u = queue.popleft()
73+
print(u, end=" ")
74+
75+
for neighbor in graph[u]:
76+
if not visited[neighbor]:
77+
visited[neighbor] = True
78+
queue.append(neighbor)
79+
80+
def bfsTraversal(graph, V, source):
81+
bfs(graph, V, source)
82+
```
83+
</TabItem>
84+
85+
<TabItem value="C++" label="C++" default>
86+
<SolutionAuthor name="@ngmuraqrdd"/>
87+
```cpp
88+
#include <iostream>
89+
#include <vector>
90+
#include <queue>
91+
#include <cstring>
92+
using namespace std;
93+
94+
void bfs(vector<int> graph[], int v, int source) {
95+
bool visited[v];
96+
memset(visited, false, sizeof(visited));
97+
queue<int> q;
98+
99+
q.push(source);
100+
visited[source] = true;
101+
102+
while (!q.empty()) {
103+
int u = q.front();
104+
q.pop();
105+
cout << u << " ";
106+
107+
for (int neighbor : graph[u]) {
108+
if (!visited[neighbor]) {
109+
visited[neighbor] = true;
110+
q.push(neighbor);
111+
}
112+
}
113+
}
114+
}
115+
116+
void bfsTraversal(vector<int> graph[], int V, int source) {
117+
bfs(graph, V, source);
118+
}
119+
```
120+
</TabItem>
121+
</Tabs>
122+
123+
## Solution Logic
124+
125+
1. **Initialize visited array and queue**: Create an array to mark visited vertices initially as False and a queue to store vertices to be visited.
126+
2. **Perform BFS**: Start BFS traversal from the source vertex.
127+
3. **Enqueue source**: Enqueue the source vertex into the queue and mark it as visited.
128+
4. **Process vertices**: While the queue is not empty, dequeue a vertex, print it, and enqueue its unvisited adjacent vertices.
129+
130+
## Time Complexity
131+
132+
$O(V + E)$, where V is the number of vertices and E is the number of edges in the graph. Each vertex and edge are visited only once.
133+
134+
## Space Complexity
135+
136+
$O(V)$, where V is the number of vertices. The space is used to store the visited array and the queue.
137+
138+
## Resources
139+
140+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/)
141+
- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
142+
- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/)
143+
144+
This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow.
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
---
2+
id: Check-for-balanced-tree
3+
title: Check for Balanced Tree (Geeks for Geeks)
4+
sidebar_label: Check for Balanced Tree
5+
tags:
6+
- Intermediate
7+
- Tree
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- DSA
12+
description: "This is a solution to the Check for Balanced Tree problem on Geeks for Geeks."
13+
---
14+
15+
## Problem Description
16+
17+
Given a binary tree, determine if it is height-balanced. A binary tree is height-balanced if the left and right subtrees of every node differ in height by no more than 1.
18+
19+
## Examples
20+
21+
**Example 1:**
22+
```
23+
Input:
24+
1
25+
/ \
26+
2 3
27+
/ \
28+
4 5
29+
Output: Yes
30+
```
31+
32+
**Example 2:**
33+
```
34+
Input:
35+
10
36+
/ \
37+
20 30
38+
/ \
39+
40 60
40+
\
41+
70
42+
Output: No
43+
```
44+
45+
## Your Task
46+
47+
Your task is to complete the function `isBalanced()`, which takes the root of the binary tree as its argument and returns a boolean value indicating whether the tree is balanced or not.
48+
49+
Expected Time Complexity: $O(N)$.
50+
Expected Auxiliary Space: $O(h)$, where h is the height of the tree.
51+
52+
## Constraints
53+
54+
- $1 <= number of nodes <= 10^5$
55+
- $1 <= data of node <= 10^5$
56+
57+
## Problem Explanation
58+
59+
Here's the step-by-step breakdown of the checking process:
60+
61+
1. **Recursive depth calculation**: Create a helper function to calculate the depth of each subtree.
62+
2. **Height difference check**: Check the difference in height between the left and right subtrees.
63+
3. **Recursive balance check**: Recursively check if each subtree is balanced.
64+
4. **Return result**: Return True if the tree is balanced, otherwise False.
65+
66+
### Code Implementation
67+
68+
<Tabs>
69+
<TabItem value="Python" label="Python" default>
70+
<SolutionAuthor name="@ngmuraqrdd"/>
71+
```py
72+
class TreeNode:
73+
def __init__(self, val=0, left=None, right=None):
74+
self.val = val
75+
self.left = left
76+
self.right = right
77+
78+
def isBalanced(root):
79+
def check(root):
80+
if not root:
81+
return 0, True
82+
left_height, left_balanced = check(root.left)
83+
right_height, right_balanced = check(root.right)
84+
balanced = left_balanced and right_balanced and abs(left_height - right_height) <= 1
85+
return max(left_height, right_height) + 1, balanced
86+
87+
return check(root)[1]
88+
```
89+
</TabItem>
90+
91+
<TabItem value="C++" label="C++" default>
92+
<SolutionAuthor name="@ngmuraqrdd"/>
93+
```cpp
94+
struct TreeNode {
95+
int val;
96+
TreeNode *left;
97+
TreeNode *right;
98+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
99+
};
100+
101+
class Solution {
102+
public:
103+
bool isBalanced(TreeNode* root) {
104+
return checkHeight(root) != -1;
105+
}
106+
107+
int checkHeight(TreeNode* root) {
108+
if (root == NULL) return 0;
109+
110+
int leftHeight = checkHeight(root->left);
111+
if (leftHeight == -1) return -1;
112+
113+
int rightHeight = checkHeight(root->right);
114+
if (rightHeight == -1) return -1;
115+
116+
if (abs(leftHeight - rightHeight) > 1) return -1;
117+
118+
return max(leftHeight, rightHeight) + 1;
119+
}
120+
};
121+
```
122+
</TabItem>
123+
</Tabs>
124+
125+
## Solution Logic
126+
127+
1. **Recursive depth calculation**: A helper function calculates the height of the subtree rooted at each node.
128+
2. **Height difference check**: For each node, the function checks if the height difference between the left and right subtrees is more than 1.
129+
3. **Recursive balance check**: The function is recursively called on each subtree to ensure both are balanced.
130+
4. **Return result**: The function returns True if all nodes are balanced, otherwise False.
131+
132+
## Time Complexity
133+
134+
$O(N)$, where N is the number of nodes in the tree. The function visits each node once.
135+
136+
## Space Complexity
137+
138+
$O(h)$, where h is the height of the tree. This is due to the recursive stack space used during the depth-first traversal.
139+
140+
## Resources
141+
142+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced/)
143+
- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/balanced-binary-tree/)
144+
- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/)
145+
146+
This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow.

0 commit comments

Comments
 (0)