Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Data Structures
  • Array
  • String
  • Linked List
  • Stack
  • Queue
  • Tree
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Graph
  • Trie
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • AVL Tree
  • Red-Black Tree
  • Advanced Data Structures
Open In App
Next Article:
Find the position of the given row in a 2-D array
Next article icon

Find the unvisited positions in Array traversal

Last Updated : 10 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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, d = 4, A[] = {3, 2, 4}
Output: 1
Explanation: Position 1 will not be visited.

Input: N = 3, d = 6, A[] = {1, 3, 5}
Output: 0
Explanation: All positions will be visited.

Approach: To solve the problem follow the below idea:

The intuition is to create a visited array which keeps track of the visited positions and return the number of positions that remains unvisited in the end.

Below are the steps for the above approach:

  • Create a visited array of length equal to the number of d +1 and initialize all the elements = 0.
  • Start traversing the A[] array.
    • Now run a "for" loop for each i and mark the positions that are traversed.
    • Make the "positionstatus" == 1 for every visited position and make sure to not visit the already visited position.
  • Now traverse the "positionstatus" array and count the number of indexes with value == 0, they are unvisited positions.
  • Return the count of unvisited positions. 

Below is the code for the above approach:

C++
#include <bits/stdc++.h> using namespace std;  int unvisitedpositions(int N, int d, int A[]) {     // Create an array to track the     // status of each positions     int positionStatus[d + 1] = {0};      // Check for each position i if     // it is in range and not     // visited yet     for (int i = 0; i < N; i++) {         if (A[i] <= d && positionStatus[A[i]] == 0) {              // Mark all positions that             // the i can reach             /// as visited             for (int j = A[i]; j <= d; j += A[i]) {                 positionStatus[j] = 1;             }         }     }      // Count the number of     // unvisited positions     int positionCount = d;     for (int i : positionStatus) {         if (i == 1) {             positionCount--;         }     }      // Return the count of     // unvisited positions     return positionCount; }  // Drivers code int main() {     int N = 3;     int d = 4;     int A[] = { 3, 2, 4 };      // Function Call     int unvisited = unvisitedpositions(N, d, A);     cout << unvisited;      return 0; } 
Java
// Java code for the above approach: import java.util.*;  class GFG {     public static int unvisitedpositions(int N, int d,                                          int A[])     {          // Create an array to track the         // status of each positions         int positionStatus[] = new int[d + 1];          // Check for each position i if         // it is in range and not         // visited yet         for (int i = 0; i < N; i++) {             if (A[i] <= d && positionStatus[A[i]] == 0) {                  // Mark all positions that                 // the i can reach                 /// as visited                 for (int j = A[i]; j <= d; j += A[i]) {                     positionStatus[j] = 1;                 }             }         }          // Count the number of         // unvisited positions         int positionCount = d;         for (int i : positionStatus) {             if (i == 1) {                 positionCount--;             }         }          // Return the count of         // unvisited positions         return positionCount;     }      // Drivers code     public static void main(String[] args)     {         int N = 3;         int d = 4;         int[] A = { 3, 2, 4 };          // Function Call         int unvisited = unvisitedpositions(N, d, A);         System.out.println(unvisited);     } } 
Python3
def unvisited_positions(N, d, A):     # Create an array to track the     # status of each positions     position_status = [0] * (d + 1)      # Check for each position i if     # it is in range and not     # visited yet     for i in range(N):         if A[i] <= d and position_status[A[i]] == 0:              # Mark all positions that             # the i can reach             # as visited             for j in range(A[i], d+1, A[i]):                 position_status[j] = 1      # Count the number of     # unvisited positions     position_count = d     for i in position_status:         if i == 1:             position_count -= 1      # Return the count of     # unvisited positions     return position_count  # Driver code N = 3 d = 4 A = [3, 2, 4]  # Function Call unvisited = unvisited_positions(N, d, A) print(unvisited) 
C#
using System;  class MainClass {     static int unvisitedpositions(int N, int d, int[] A)     {         // Create an array to track the         // status of each position         int[] positionStatus = new int[d + 1];          // Check for each position i if         // it is in range and not         // visited yet         for (int i = 0; i < N; i++) {             if (A[i] <= d && positionStatus[A[i]] == 0) {                  // Mark all positions that                 // the i can reach                 // as visited                 for (int j = A[i]; j <= d; j += A[i]) {                     positionStatus[j] = 1;                 }             }         }          // Count the number of         // unvisited positions         int positionCount = d;         foreach (int i in positionStatus) {             if (i == 1) {                 positionCount--;             }         }          // Return the count of         // unvisited positions         return positionCount;     }      // Drivers code     static void Main() {         int N = 3;         int d = 4;         int[] A = { 3, 2, 4 };          // Function Call         int unvisited = unvisitedpositions(N, d, A);         Console.WriteLine(unvisited);     } } 
JavaScript
function unvisitedpositions(N, d, A) {   // Create an array to track the    // status of each position   let positionStatus = new Array(d + 1).fill(0);   // Check for each position i if    // it is in range and not    // visited yet   for (let i = 0; i < N; i++) {     if (A[i] <= d && positionStatus[A[i]] === 0) {       // Mark all positions that        // i can reach        // as visited       for (let j = A[i]; j <= d; j += A[i]) {         positionStatus[j] = 1;       }     }   }   // Count the number of    // unvisited positions   let positionCount = d;   for (let i of positionStatus) {     if (i === 1) {       positionCount--;     }   }   // Return the count of    // unvisited positions   return positionCount; } // Driver code const N = 3; const d = 4; const A = [3, 2, 4]; // Function call const unvisited = unvisitedpositions(N, d, A); console.log(unvisited); 

Output
1

Time Complexity: O(N*logN) 
Auxiliary Space: O(positions)


Next Article
Find the position of the given row in a 2-D array
author
shivammiglani09
Improve
Article Tags :
  • DSA
  • Map
Practice Tags :
  • Map

Similar Reads

  • Find the transition point in a binary array
    Given a sorted array, arr[], containing only 0s and 1s, find the transition point, i.e., the first index where 1 was observed, and before that, only 0 was observed. If arr does not have any 1, return -1. If the array does not have any 0, return 0. Examples : Input: 0 0 0 1 1Output: 3Explanation: Ind
    7 min read
  • Find the value at kth position in the generated array
    Given three integer n, m and k. Find the element at kth position after repeating the given operation n number of times. In a single operation, an integer one greater than the maximum element from the array is appended to the array and the original array gets appended after that. For example, arr[] =
    5 min read
  • Search insert position of K in a sorted array
    Given a 0-based sorted array arr[] consisting of n distinct integers and an integer k, the task is to find the index of k, if it is present in the array arr[]. Otherwise, find the index where k must be inserted to keep the array sorted. Examples: Input: arr[] = [1, 3, 5, 6], k = 5Output: 2Explanatio
    12 min read
  • Find the position of the given row in a 2-D array
    Given a matrix mat[][] of size m * n which is sorted in a row-wise fashion and an array row[], the task is to check if any row in the matrix is equal to the given array row[]. Examples: Input: mat[][] = { {1, 1, 2, 3, 1}, {2, 1, 3, 3, 2}, {2, 4, 5, 8, 3}, {4, 5, 5, 8, 3}, {8, 7, 10, 13, 6}}row[] = {
    14 min read
  • Move all zeroes to end of array | Set-2 (Using single traversal)
    Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7,
    7 min read
  • Find a partition point in array
    Given an unsorted array of integers. Find an element such that all the elements to its left are smaller and to its right are greater. Print -1 if no such element exists. Note that there can be more than one such elements. For example an array which is sorted in increasing order all elements follow t
    15 min read
  • Find the Target number in an Array
    Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities. Examples: Input: Array: {10, 20, 30, 40, 50} , Target: 30Output: "Target found at index 2" Input: A
    13 min read
  • Count inversions in an array | Set 4 ( Using Trie )
    Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] > a[j] and i <
    12 min read
  • Find the only missing number in a sorted array
    You are given a sorted array of N integers from 1 to N with one number missing find the missing number Examples: Input :ar[] = {1, 3, 4, 5}Output : 2Input : ar[] = {1, 2, 3, 4, 5, 7, 8}Output : 6A simple solution is to linearly traverse the given array. Find the point where current element is not on
    9 min read
  • How to traverse 2D arrays in JavaScript?
    A two-dimensional array or simply 2D array is a format to store data in a grid format that is rows and columns format. There is no special way of declaring a 2D array in JavaScript, we can simply pass an array as an element inside another array. the array obtained in this method will be created as a
    6 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