HackerRank : NCR CodeSprint – Counting Mistakes

By | November 6, 2016

Sam goes to Wayside School, where they teach counting according to the following rules:

  1. Always start counting at 1.
  2. Each subsequent counted item is assigned the value of 1 more than the previously counted item.

Consider n=5 stars:

counting-stars-1.png

Using Wayside’s method of counting, we count the stars like so:

counting-stars-2.png

Observe that the number assigned to a star during counting is always 1 more than the number assigned to the previously counted star. This means that if one star is incorrectly numbered during counting, the number assigned si to star is considered to be correct as long as si= si-1 + 1 .

If a student doesn’t make any mistakes, Wayside School’s counting looks just like regular counting; however, Sam tends to make a lot of mistakes. For example, he counted the above stars like this:

counting-stars-3.png

In the diagram above, Sam made the following two counting mistakes:

  1. He added 0 (instead of  1) to s2 when counting star s3 .
  2. He added 4  (instead of 1) to s4 when counting star s5.

Note that Sam’s count of star s4 is correct because he counted s4 as 1  more than s3 (even though he counted  s3 incorrectly.

Sam’s teacher wants your help determining how many mistakes he makes when counting n stars. Given the value of  n and Sam’s count sequence for n stars, find and print the number of mistakes he made according to Wayside counting.

Input Format

The first line contains an integer, n, denoting the number of stars Sam counts.
The second line contains n space-separated integers describing the respective values Sam counted .

Constraints

 1 <=n <= 10^3
 1 <=si <= 10^3

Output Format

Print a single integer denoting the number of mistakes Sam made using Wayside counting.

Sample Input 0

4
3 4 7 7

Sample Output 0

3

Explanation 0
Sam makes the following three mistakes:

  1. He started counting s1 at 3 instead of 1 .
  2. He added 3  (instead of 1) to s2 when counting star s3 .
  3. He added 0(instead of 1) to s3 when counting star s4.

Thus, we print as our answer.

Sample Input 1

5
1 3 2 3 4

Sample Output 1

2

Explanation 1
Sam makes the following two mistakes:

  1. He added 2(instead of 1) to s1 when counting star s2.
  2. He added -1(instead of 1) to s2 when counting star s3.

Thus, we print 2as our answer.

Solution

Solution for this problem is pretty simple. 
I have taken a variable mis as zero.
if the first element of array is not 1, then mistake count is 
increased.
Now checked every positioned element in array that if it is equal 
to 1 plus its previous array element, if not then mistake count 
is increased.
Finally print the mistake count.