Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count unvisited leaves after Frog Jumps
Next article icon

Count unvisited leaves after Frog Jumps

Last Updated : 04 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of size N, an integer K representing the number of leaves in the pond, and the arr[i] indicating the strength of the ith frog's jump, where 0 <= i < N. The frogs are at one end of the pond and are trying to get to the other end by jumping on the leaves, the task is to count the number of unvisited leaves. After each frog has reached the end while ensuring that every frog jumps with its respective strength.

Examples:

Input: N = 3 , K = 4 , arr [ ] = {3, 2, 4} 
Output: 1
Explanation: leaf 2 will be visited by Frog 1, leaf 3 will be visited by frog 0, leaf 4 will be visited by Frog 1, and Frog 2, only leaf 1 remains unvisited.

Input: N = 3 , K = 6 , arr [ ] = {1, 3, 5} 
Output: 0
Explanation: Frog 0 will visit all the leaves as it jumps a distance of 1, so no leaf remains unvisited.

Naive Approach: We can follow the below idea to solve the problem :

The problem states to find the count of leaves which are unvisited after all the N frogs have crossed the pond. For each frog i with strength strengthi we can iterate over the n leaves starting from 0 where the frog is currently present by jumping the frog from it's present_leaf to present_leaf + strengthi (the next leaf it will jump on to), which will be the next present_leaf for this ith frog. Thus we can mark the leaves which are visited by this ith frog (the leaf with index that are perfectly divisible by strength of frog i). Similarly after iterating over all the frogs we marked all the leaves that were visited during the crossing of the frogs.

Follow the steps to solve the problem:

  • Initialize the visited vector of size leaves+1, and mark them as false
  • For each frog, iterate over all the leaves that the frog will visit, and mark that leaf as visited
  • Iterate over all the leaves, and increase the answer count by 1 when an unvisited leaf is found

Below is the implementation for the above approach:

C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;  int unvisitedLeaves(int N, int leaves, int frogs[]) {      // Initialising visited vector for leaves, and     // marking them as not vistied initially     vector<bool> visited(leaves + 1, false);      // Iterating over all frogs     for (int i = 0; i < N; ++i) {         int strength_i = frogs[i];          // Going through all the leaves ith frog         // will visit and mark the leaves as visited         for (int j = 0; j <= leaves; j++) {             if (j % strength_i == 0)                 visited[j] = true;         }     }      // Iterating over all the leaves     // and if the leaf is not visited, increasing     // our count by 1     int unvisitedLeavesCount = 0;     for (int i = 0; i <= leaves; ++i) {         if (visited[i] == false) {             unvisitedLeavesCount++;         }     }      return unvisitedLeavesCount; }  // Drivers code int main() {     int N = 3;     int leaves = 6;     int frogs[N] = { 3, 6, 2 };      // Function call     cout << unvisitedLeaves(N, leaves, frogs) << endl;     return 0; } 
Java
import java.util.*;  public class GFG {      static int unvisitedLeaves(int N, int leaves, int[] frogs) {         // Initialising visited array for leaves and         // marking them as not visited initially         boolean[] visited = new boolean[leaves + 1];          // Iterating over all frogs         for (int i = 0; i < N; ++i) {             int strength_i = frogs[i];              // Going through all the leaves ith frog             // will visit and mark the leaves as visited             for (int j = 0; j <= leaves; j++) {                 if (j % strength_i == 0)                     visited[j] = true;             }         }          // Iterating over all the leaves         // and if the leaf is not visited, increasing         // our count by 1         int unvisitedLeavesCount = 0;         for (int i = 0; i <= leaves; ++i) {             if (!visited[i]) {                 unvisitedLeavesCount++;             }         }          return unvisitedLeavesCount;     }      // Drivers code     public static void main(String[] args) {         int N = 3;         int leaves = 6;         int[] frogs = {3, 6, 2};          // Function call         System.out.println(unvisitedLeaves(N, leaves, frogs));     } } 
Python
def unvisitedLeaves(N, leaves, frogs):     # Initializing visited list for leaves, and     # marking them as not visited initially     visited = [False] * (leaves + 1)      # Iterating over all frogs     for i in range(N):         strength_i = frogs[i]          # Going through all the leaves ith frog         # will visit and mark the leaves as visited         for j in range(leaves + 1):             if j % strength_i == 0:                 visited[j] = True      # Iterating over all the leaves     # and if the leaf is not visited, increasing     # our count by 1     unvisitedLeavesCount = 0     for i in range(leaves + 1):         if not visited[i]:             unvisitedLeavesCount += 1      return unvisitedLeavesCount  # Driver code if __name__ == "__main__":     N = 3     leaves = 6     frogs = [3, 6, 2]      # Function call     print(unvisitedLeaves(N, leaves, frogs)) 
C#
// C# Implementation: using System;  public class GFG {     static int UnvisitedLeaves(int N, int leaves, int[] frogs)     {         // Initialising visited array for leaves and         // marking them as not visited initially         bool[] visited = new bool[leaves + 1];          // Iterating over all frogs         for (int i = 0; i < N; ++i)         {             int strength_i = frogs[i];              // Going through all the leaves ith frog             // will visit and mark the leaves as visited             for (int j = 0; j <= leaves; j++)             {                 if (j % strength_i == 0)                     visited[j] = true;             }         }          // Iterating over all the leaves         // and if the leaf is not visited, increasing         // our count by 1         int unvisitedLeavesCount = 0;         for (int i = 0; i <= leaves; ++i)         {             if (!visited[i])             {                 unvisitedLeavesCount++;             }         }          return unvisitedLeavesCount;     }      // Drivers code     public static void Main(string[] args)     {         int N = 3;         int leaves = 6;         int[] frogs = { 3, 6, 2 };          // Function call         Console.WriteLine(UnvisitedLeaves(N, leaves, frogs));     } } // This code is contributed by Sakshi 
JavaScript
function GFG(N, leaves, frogs) {     // Initialising visited array for the leaves and     // marking them as not visited initially     const visited = new Array(leaves + 1).fill(false);     // Iterating over all frogs     for (let i = 0; i < N; ++i) {         const strength_i = frogs[i];         for (let j = 0; j <= leaves; j++) {             if (j % strength_i === 0)                 visited[j] = true;         }     }     // Iterating over all the leaves     // and if the leaf is not visited      // increasing our count by 1     let unvisitedLeavesCount = 0;     for (let i = 0; i <= leaves; ++i) {         if (!visited[i]) {             unvisitedLeavesCount++;         }     }     return unvisitedLeavesCount; } // Driver code const N = 3; const leaves = 6; const frogs = [3, 6, 2]; // Function call console.log(GFG(N, leaves, frogs)); 

Output
2

Time Complexity: O(N.leaves)
Auxiliary Space: O(N)

Efficient Approach: To solve the problem using the Sieve Approach:

Since each frog is crossing the pond, there will be leaves that have been visited by another frog already. For those leaves, we do not need to traverse the ponds for such a frog for marking the leaves it visits as true, as they have already been marked true by a frog before it.

Let's take an example: N = 3 , leaves = 6 , frogs = [ 3, 6, 2 ]

Screenshot-2023-06-24-214002.png

Let's look for the first frog with strength 3 :

2.png

3.png

4.png

It jumps to 3, then 6, then so on until it reaches the other side of the pond, in this case after 6, in the next jump it reaches the other side.

Now for the next frog with strength 6:

5.pngthe

6.png

In the first jump, it goes to 6 and marks it as visited. Now if the leaves were more, we can observe that since 3 (strength of frog 1) is a factor of 6(strength of frog 2), frog 1 will visit all the leaves that frog 2 will visit. Thus we can skip the iteration for frog 2, and still mark all the leaves that were going to be visited.

Follow the steps to solve the problem:

  • Sort Strength in increasing order
  • Initialize the visited vector of size leaves+1, and mark them as false
  • Initialize the count of unvisited leaves by the total number of leaves
  • For each frog, check if the leaf jumped on after the first jump of the frog visited or not. (If in the first jump, it reaches the other end, skip this frog as well, as it will not visit any leaves). If it is visited, skip the iteration for this frog. Else, iterate over all the leaves this frog is going to, mark them as visited, and decrease the number of unvisited leaves by 1.

Below is the implementation for the above approach:

C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;  int unvisitedLeaves(int N, int leaves, int frogs[]) {      // Initialising visited vector for leaves,     // and marking them as not vistied initially     vector<bool> visited(leaves + 1, false);      // Intialising unvisited leaevs count by total     // number of leaves     int unvisitedLeavesCount = leaves;      // Sorting strength of frogs in increasing order     sort(frogs, frogs + N);      // Iterating over all frogs     for (int i = 0; i < N; ++i) {         int strength_i = frogs[i];          // If strength is 1, the frg is going to         // visit all leaves so we can return 0,         // since no leaves is going to be left unvisited         if (strength_i == 1)             return 0;          // Skipping iteration for this frog as it         // will not visit any leaf         if (strength_i > leaves)             continue;          // Skipping iteration as leaves for this         // frog are already visited         if (visited[strength_i] == true)             continue;          // If leaves of this frog are not visited         // We go through all the leaves ith frog         // will visit and mark the leaves as visited         for (int j = strength_i; j <= leaves;              j += strength_i) {              // Decreasing number of leaves not             // visited by 1 if the leaf is not visited             // in any jump of other frog             if (visited[j] == false)                 unvisitedLeavesCount--;              // Marking leaf as visited             visited[j] = true;         }     }      return unvisitedLeavesCount; }  // Drivers code int main() {     int N = 3;     int leaves = 6;     int frogs[N] = { 3, 6, 2 };      // Function call     cout << unvisitedLeaves(N, leaves, frogs) << endl;     return 0; } 
Java
import java.util.Arrays;  public class Main {      // Function to calculate the number of unvisited leaves     static int unvisitedLeaves(int N, int leaves, int[] frogs) {          // Initializing visited array for leaves and marking them as not visited initially         boolean[] visited = new boolean[leaves + 1];          // Initializing unvisited leaves count by the total number of leaves         int unvisitedLeavesCount = leaves;          // Sorting the strength of frogs in increasing order         Arrays.sort(frogs);          // Iterating over all frogs         for (int i = 0; i < N; ++i) {             int strength_i = frogs[i];              // If strength is 1, the frog is going to visit all leaves,             // so we can return 0 since no leaves will be left unvisited             if (strength_i == 1)                 return 0;              // Skipping iteration for this frog as it will not visit any leaf             if (strength_i > leaves)                 continue;              // Skipping iteration as leaves for this frog are already visited             if (visited[strength_i])                 continue;              // If leaves of this frog are not visited,             // we go through all the leaves ith frog will visit and mark the leaves as visited             for (int j = strength_i; j <= leaves; j += strength_i) {                  // Decreasing the number of leaves not visited by 1 if the leaf is not visited                 // in any jump of other frogs                 if (!visited[j])                     unvisitedLeavesCount--;                  // Marking leaf as visited                 visited[j] = true;             }         }          return unvisitedLeavesCount;     }      // Driver code     public static void main(String[] args) {         int N = 3;         int leaves = 6;         int[] frogs = {3, 6, 2};          // Function call         System.out.println(unvisitedLeaves(N, leaves, frogs));     } } 
Python3
# Python code for the above approach: def unvisited_leaves(N, leaves, frogs):     # Initializing visited list for leaves,     # and marking them as not visited initially     visited = [False] * (leaves + 1)      # Initializing unvisited leaves count by the total     # number of leaves     unvisited_leaves_count = leaves      # Sorting the strength of frogs in increasing order     frogs.sort()      # Iterating over all frogs     for i in range(N):         strength_i = frogs[i]          # If strength is 1, the frog is going to         # visit all leaves, so we can return 0         if strength_i == 1:             return 0          # Skipping iteration for this frog as it         # will not visit any leaf         if strength_i > leaves:             continue          # Skipping iteration as leaves for this         # frog are already visited         if visited[strength_i]:             continue          # If leaves of this frog are not visited         # we go through all the leaves this frog         # will visit and mark the leaves as visited         for j in range(strength_i, leaves + 1, strength_i):             # Decreasing the number of leaves not             # visited by 1 if the leaf is not visited             # in any jump of other frog             if not visited[j]:                 unvisited_leaves_count -= 1              # Marking the leaf as visited             visited[j] = True      return unvisited_leaves_count  # Driver code if __name__ == "__main__":     N = 3     leaves = 6     frogs = [3, 6, 2]      # Function call     print(unvisited_leaves(N, leaves, frogs)) 
C#
using System;  class Program {     static int UnvisitedLeaves(int N, int leaves, int[] frogs)     {         // Initializing visited array for leaves,         // and marking them as not visited initially         bool[] visited = new bool[leaves + 1];          // Initializing unvisited leaves count by total         // number of leaves         int unvisitedLeavesCount = leaves;          // Sorting strength of frogs in increasing order         Array.Sort(frogs);          // Iterating over all frogs         for (int i = 0; i < N; ++i)         {             int strength_i = frogs[i];              // If strength is 1, the frog is going to             // visit all leaves, so we can return 0,             // since no leaves are going to be left unvisited             if (strength_i == 1)                 return 0;              // Skipping iteration for this frog as it             // will not visit any leaf             if (strength_i > leaves)                 continue;              // Skipping iteration as leaves for this             // frog are already visited             if (visited[strength_i])                 continue;              // If leaves of this frog are not visited             // We go through all the leaves ith frog             // will visit and mark the leaves as visited             for (int j = strength_i; j <= leaves; j += strength_i)             {                 // Decreasing number of leaves not                 // visited by 1 if the leaf is not visited                 // in any jump of other frog                 if (!visited[j])                     unvisitedLeavesCount--;                  // Marking leaf as visited                 visited[j] = true;             }         }          return unvisitedLeavesCount;     }      // Driver code     static void Main()     {         int N = 3;         int leaves = 6;         int[] frogs = { 3, 6, 2 };          // Function call         Console.WriteLine(UnvisitedLeaves(N, leaves, frogs));     } } 
JavaScript
// Javascript program for the above approach function unvisitedLeaves(N, leaves, frogs) {   // Initializing visited array for leaves,   // and marking them as not visited initially   let visited = Array(leaves + 1).fill(false);    // Initializing unvisited leaves count by total   // number of leaves   let unvisitedLeavesCount = leaves;    // Sorting strength of frogs in increasing order   frogs.sort((a, b) => a - b);    // Iterating over all frogs   for (let i = 0; i < N; ++i) {     let strength_i = frogs[i];      // If strength is 1, the frog is going to     // visit all leaves so we can return 0,     // since no leaves are going to be left unvisited     if (strength_i === 1) {       return 0;     }      // Skipping iteration for this frog as it     // will not visit any leaf     if (strength_i > leaves) {       continue;     }      // Skipping iteration as leaves for this     // frog are already visited     if (visited[strength_i]) {       continue;     }      // If leaves of this frog are not visited     // We go through all the leaves ith frog     // will visit and mark the leaves as visited     for (let j = strength_i; j <= leaves; j += strength_i) {       // Decreasing the number of leaves not       // visited by 1 if the leaf is not visited       // in any jump of other frog       if (!visited[j]) {         unvisitedLeavesCount--;       }        // Marking leaf as visited       visited[j] = true;     }   }    return unvisitedLeavesCount; }  // Driver code let N = 3; let leaves = 6; let frogs = [3, 6, 2];  // Function call console.log(unvisitedLeaves(N, leaves, frogs));  // This code is contributed by Susobhan Akhuli 

Output
2

Time Complexity: O(N.log(N) + N*leaves*log(log(leaves))), N.log(N) for sorting strength of frogs. N*(leaves*log(log(leaves))) for iterating over the leaves. So the total time complexity would be a max of N.log(N), N*(leaves*log(log(leaves))).
Auxiliary Space: O(N)


Next Article
Count unvisited leaves after Frog Jumps

S

shide
Improve
Article Tags :
  • Mathematical
  • DSA
  • sieve
Practice Tags :
  • Mathematical
  • sieve

Similar Reads

    Count all possible visited cells of a knight after N moves
    Given the current position of a Knight as (i, j), find the count of different possible positions visited by a knight after N moves (in a 10 x 10 board). Examples: Input: i = 3, j = 3, n = 1 Output: 9 The Knight is initially at position [3][3]. After one move it can visit 8 more cells Input: i = 3, j
    8 min read
    Find the unvisited positions in Array traversal
    Given an array A[] of N positive integers where A[i] represent the units each i can traverse in one step. You can start from position 0 and need to reach destination d. The goal is to find the number of positions that are not visited when all of them have reached position d. Examples: Input: N = 3,
    6 min read
    Frog Jump - Climbing Stairs with Cost
    Given an integer array height[] where height[i] represents the height of the i-th stair, a frog starts from the first stair and wants to reach the top. From any stair i, the frog has two options: it can either jump to the (i+1)-th stair or the (i+2)-th stair. The cost of a jump is the absolute diffe
    15+ min read
    Unreachable leaves by frogs
    Given N frogs, M leaves, and strength K for each frog. The task is to find the number of leaves that cannot be visited by any of the frogs when all frogs have reached the other end of the pond where each frog has the strength to jump exactly K leaves. Examples: Input: N = 3, M = 4, frogs[] = {3, 2,
    4 min read
    Last node at which Frog is standing after t seconds
    Given a Tree consists of n (1<=n<=100) vertices numbered from 1 to n. The given tree is rooted at vertex-1 and the tree edges are given in an array of edges. A frog is standing at vertex-1 and a timer t is given to it. Given edges of the undirected tree as array edges, where edges[i] = [u, v]
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences