# Java Program to Find the Lost Number

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

*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.*

**n****Examples**

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.

**Approach**

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.

**Algorithm**

- Take the input as string.
- Count the number of spaces present in the string.
- If the number of spaces present is equal to any of the element present in the array then print that number else print -1.
- 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

I**mplementation:**

## Java

`// 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);` ` ` `else` ` ` `System.out.println(-` `1` `);` ` ` `}` ` ` ` ` `public` `static` `void` `main(String args[])` ` ` `{` ` ` `Scanner in = ` `new` `Scanner(System.in);` ` ` ` ` `// Taking input as string` ` ` `String s = ` `"5 7 4 3 2 6"` `;` ` ` ` ` `findLostCount(s);` ` ` `}` `}` |

**Output**

Number of elements 5

Attention reader! Don’t stop learning now. Get hold of all the important **Java Foundation** and Collections concepts with the **Fundamentals of Java and Java Collections Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**