Skip to content
Related Articles
Open in App
Not now

Related Articles

Java Program to Find the Lost Number

Improve Article
Save Article
  • Last Updated : 04 Jan, 2021
Improve Article
Save Article

Bob is a small kid and just learned to count numbers. He sat in his house and started playing with his number of toys. He was having some n toy numbers on his left and the count of those n toys in the right hand. Suddenly his mother called him, and he mixed all the numbers and left. When he returned he realized that he forgot the count of the numbers he was having. Given all the toy numbers help him find the value of n if present in the array or print -1.


Input: 5 7 4 3 2 6

Output: 5

Explanation: There are 6 toy numbers out of which one is the length hence we print 5.

Input: 10 14 11 15

Output: -1

Explanation: There are 4 toy numbers but we do not have 3 as the value in the array hence we print -1.


The solution is pretty simple. We can just take the input in a string and count the number of spaces, which will be the actual length of the array.


  1. Take the input as string.
  2. Count the number of spaces present in the string.
  3. If the number of spaces present is equal to any of the element present in the array then print that number else print -1.
  4. To find the element is present or not, we use string.indexOf() method.

How does it work?

  • When we take the input as a string the number of elements present in the string is equal to the number of spaces present +1.
  • The actual number of elements is equal to the number of elements present in the string -1.

Required answer = number of spaces +1 -1 = number of spaces



// Java program to find the lost count
import java.util.*;
public class GFG {
    // find lost count
    public static void findLostCount(String s)
        // counting the number of elements using the split
        // function -1
        int count = s.split(" ").length - 1;
        // if the value count is present then print count
        // else print -1
        if (s.indexOf(Integer.toString(count)) != -1)
            System.out.println("Number of elements "
                               + count);
    public static void main(String args[])
        Scanner in = new Scanner(;
        // Taking input as string
        String s = "5 7 4 3 2 6";


Number of elements 5

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!