Count the number of nodes in a Graph whose sum of neighbors is at most K
Last Updated :
09 Feb, 2023
Given a graph root, and a value K, the task is to find the number of nodes in the graph whose sum of neighbors is less than K.
Example:
Input: root = 8 K = 14
/ \
2---3 7---3
/ \ \
5 6 0
\ \ / \
1 2 6 9
Output: 10
Explanation: Nodes with sum of neighbors less than 14 are the nodes with value 8, 7, 6, 9, 3(rightmost), 2, 5, 1, 6, 2
Input: root = 2 K = 5
/ \
3 1
/ \
5 6
Output: 3
Approach: The given problem can be solved by using the depth-first search on the graph. The idea is to use recursion and visit every node to check the sum of its neighbor node is less than K. Below steps can be followed to solve the problem:
- Use recursion to apply depth-first search on the graph and use a hashset to store the visited nodes of the graph
- At every node iterate through the neighbors of that node and add their sum
- If the sum is greater than K then increment the count
- Return the count as the result
Below is the implementation of the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
vector<Node *> neighbors;
int val;
Node(int v)
{
val = v;
neighbors = {};
}
};
// Depth first search function to visit
// every node of the graph and check if
// sum of neighbor nodes is less than K
void dfs(
Node *root,
set<Node *> &visited,
vector<int> &count, int K)
{
// If the current node is
// already visited then return
if (visited.find(root) != visited.end())
return;
// Mark the current node as visited
visited.insert(root);
// Initialize a variable sum to
// calculate sum of neighbors
int sum = 0;
// Iterate through all neighbors
for (Node *n : root->neighbors)
{
sum += n->val;
}
// If sum is less than K then
// increment count by 1
if (sum < K)
count[0] = count[0] + 1;
for (Node *n : root->neighbors)
{
// Visit the neighbor nodes
dfs(n, visited, count, K);
}
}
// Function to find the number of nodes
// in the graph with sum less than K
int nodeSumLessThanK(
Node *root, int K)
{
// Initialize the variable count
// to count the answer
vector<int> count(1, 0);
// Initialize a HashSet to
// store the visited nodes
set<Node *> visited;
// Apply DFS on the graph
dfs(root, visited, count, K);
// Return the answer stored in count
return count[0];
}
// Driver code
int main()
{
// Initialize the graph
Node *root = new Node(2);
root->neighbors.push_back(new Node(3));
root->neighbors.push_back(new Node(1));
root->neighbors[0]->neighbors.push_back(new Node(5));
root->neighbors[1]->neighbors.push_back(new Node(6));
int K = 5;
// Call the function
// and print the result
cout << (nodeSumLessThanK(root, K));
return 0;
}
// This code is contributed by Potta Lokesh
Java
// Java implementation for the above approach
import java.io.*;
import java.util.*;
class GFG {
static class Node {
List<Node> neighbors;
int val;
public Node(int val)
{
this.val = val;
neighbors = new ArrayList<>();
}
}
// Function to find the number of nodes
// in the graph with sum less than K
public static int nodeSumLessThanK(
Node root, int K)
{
// Initialize the variable count
// to count the answer
int[] count = new int[1];
// Initialize a HashSet to
// store the visited nodes
Set<Node> visited = new HashSet<>();
// Apply DFS on the graph
dfs(root, visited, count, K);
// Return the answer stored in count
return count[0];
}
// Depth first search function to visit
// every node of the graph and check if
// sum of neighbor nodes is less than K
public static void dfs(
Node root,
Set<Node> visited,
int[] count, int K)
{
// If the current node is
// already visited then return
if (visited.contains(root))
return;
// Mark the current node as visited
visited.add(root);
// Initialize a variable sum to
// calculate sum of neighbors
int sum = 0;
// Iterate through all neighbors
for (Node n : root.neighbors) {
sum += n.val;
}
// If sum is less than K then
// increment count by 1
if (sum < K)
count[0]++;
for (Node n : root.neighbors) {
// Visit the neighbor nodes
dfs(n, visited, count, K);
}
}
// Driver code
public static void main(String[] args)
{
// Initialize the graph
Node root = new Node(2);
root.neighbors.add(new Node(3));
root.neighbors.add(new Node(1));
root.neighbors.get(0)
.neighbors.add(new Node(5));
root.neighbors.get(1)
.neighbors.add(new Node(6));
int K = 5;
// Call the function
// and print the result
System.out.println(
nodeSumLessThanK(root, K));
}
}
Python3
# Python code for the above approach
# Class to represent a node
class Node:
def __init__(self, v):
self.val = v
self.neighbors = []
# Depth first search function to visit
# every node of the graph and check if
# sum of neighbor nodes is less than K
def dfs(root, visited, count, K):
# If the current node is
# already visited then return
if root in visited:
return
# Mark the current node as visited
visited.add(root)
# Initialize a variable sum to
# calculate sum of neighbors
sum = 0
# Iterate through all neighbors
for n in root.neighbors:
sum += n.val
# If sum is less than K then
# increment count by 1
if sum < K:
count[0] += 1
for n in root.neighbors:
# Visit the neighbor nodes
dfs(n, visited, count, K)
# Function to find the number of nodes
# in the graph with sum less than K
def nodeSumLessThanK(root, K):
# Initialize the variable count
# to count the answer
count = [0]
# Initialize a set to store
# the visited nodes
visited = set()
# Apply DFS on the graph
dfs(root, visited, count, K)
# Return the answer stored in count
return count[0]
# Driver code
# Initialize the graph
root = Node(2)
root.neighbors.append(Node(3))
root.neighbors.append(Node(1))
root.neighbors[0].neighbors.append(Node(5))
root.neighbors[1].neighbors.append(Node(6))
K = 5
# Call the function
# and print the result
print(nodeSumLessThanK(root, K))
C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
public class GFG {
class Node {
public List<Node> neighbors;
public int val;
public Node(int val)
{
this.val = val;
neighbors = new List<Node>();
}
}
// Function to find the number of nodes
// in the graph with sum less than K
static int nodeSumLessThanK(
Node root, int K)
{
// Initialize the variable count
// to count the answer
int[] count = new int[1];
// Initialize a HashSet to
// store the visited nodes
HashSet<Node> visited = new HashSet<Node>();
// Apply DFS on the graph
dfs(root, visited, count, K);
// Return the answer stored in count
return count[0];
}
// Depth first search function to visit
// every node of the graph and check if
// sum of neighbor nodes is less than K
static void dfs(
Node root,
HashSet<Node> visited,
int[] count, int K)
{
// If the current node is
// already visited then return
if (visited.Contains(root))
return;
// Mark the current node as visited
visited.Add(root);
// Initialize a variable sum to
// calculate sum of neighbors
int sum = 0;
// Iterate through all neighbors
foreach (Node n in root.neighbors) {
sum += n.val;
}
// If sum is less than K then
// increment count by 1
if (sum < K)
count[0]++;
foreach (Node n in root.neighbors) {
// Visit the neighbor nodes
dfs(n, visited, count, K);
}
}
// Driver code
public static void Main(String[] args)
{
// Initialize the graph
Node root = new Node(2);
root.neighbors.Add(new Node(3));
root.neighbors.Add(new Node(1));
root.neighbors[0]
.neighbors.Add(new Node(5));
root.neighbors[1]
.neighbors.Add(new Node(6));
int K = 5;
// Call the function
// and print the result
Console.WriteLine(
nodeSumLessThanK(root, K));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript code for the above approach
class Node {
constructor(v) {
this.val = v;
this.neighbors = [];
}
};
// Depth first search function to visit
// every node of the graph and check if
// sum of neighbor nodes is less than K
function dfs(root, visited, count, K) {
// If the current node is
// already visited then return
if (visited.has(root))
return;
// Mark the current node as visited
visited.add(root);
// Initialize a variable sum to
// calculate sum of neighbors
let sum = 0;
// Iterate through all neighbors
for (let n of root.neighbors) {
sum += n.val;
}
// If sum is less than K then
// increment count by 1
if (sum < K)
count[0] = count[0] + 1;
for (let n of root.neighbors) {
// Visit the neighbor nodes
dfs(n, visited, count, K);
}
}
// Function to find the number of nodes
// in the graph with sum less than K
function nodeSumLessThanK(root, K) {
// Initialize the variable count
// to count the answer
let count = new Array(1).fill(0);
// Initialize a HashSet to
// store the visited nodes
let visited = new Set();
// Apply DFS on the graph
dfs(root, visited, count, K);
// Return the answer stored in count
return count[0];
}
// Driver code
// Initialize the graph
let root = new Node(2);
root.neighbors.push(new Node(3));
root.neighbors.push(new Node(1));
root.neighbors[0].neighbors.push(new Node(5));
root.neighbors[1].neighbors.push(new Node(6));
let K = 5;
// Call the function
// and print the result
document.write(nodeSumLessThanK(root, K));
// This code is contributed by gfgking.
</script>
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph
Auxiliary Space: O(V)
Similar Reads
Maximum number of nodes which can be reached from each node in a graph. Given a graph with N nodes and K bidirectional edges between them find the number of nodes which can be reachable from a particular. Two nodes X and Y are said to be reachable if we can start at X and end at Y using any number of edges. Note : A Node is reachable to itself. Input : N = 7 1 5 \ / \ 2
9 min read
Find the number of paths of length K in a directed graph Given a directed, unweighted graph with N vertices and an integer K. The task is to find the number of paths of length K for each pair of vertices (u, v). Paths don't have to be simple i.e. vertices and edges can be visited any number of times in a single path. The graph is represented as adjacency
9 min read
Count of all valid combinations of at most K numbers that sum up to N Given two numbers N and K, the task is to find the count of all valid combinations of at most K numbers that sum up to N such that the following conditions are true: Only numbers 1 through 9 are used.Each number is used at most once. Examples: Input: K = 3, N = 7Output: 5Explanation:1 2 41 62 53 47
7 min read
Count nodes with maximum reachable neighbours at a d distance Given a graph with n nodes and m edges, each edges[i] = [u, v, weight] and d as the maximum distance to reach the neighbor nodes, the task is to find the total number of nodes with maximum reachable neighbors. Input: n = 4, edges = [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]], d = 4 Example 1 Output
10 min read
Count of nodes with average of left subtree at least K in a given Binary Tree Given a binary tree and a number K, the task is to count the number of nodes having the average of the values in their left subtree greater than or equal to K. Examples: Input : K=5Tree: 2 / \ 5 4 / \ / \ 5 6 6 2 \ / 5 4Output: 3Explanation: 2 -------- level 0 / \ 5 4 -------- level 1 / \ / \ 5 6 6
15+ min read