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
Explanation: There are 6 toy numbers out of which one is the length hence we print 5.
Input: 10 14 11 15
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.
- 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
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.