Thursday 18 June 2015

CODILITY.COM - LESSON 2 - FrogRiverOne

Codility.com

PROBLEM:
A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.
You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.
For example, you are given integer X = 5 and array A such that:
  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4
In minute 6, a leaf falls into position 5. 

MY SOLUTION (100% score, time complexity O(n))
using System.Collections.Generic;
using System.Linq;
class Solution {
    public int solution(int X, int[] A) {
        int [] B = A.Distinct().ToArray();        
        return (B.Length != X)? -1 : Array.IndexOf(A, B[B.Length-1]);
    }
}

We are only interested in knowing when the first X position (leave) falls and if all the other leaves (from 1 to X-1) have already occurred. For that I copy the array into a new one without any position that is repeated, as it does not matter (arrayName.Distinct().ToArray()).

Condition to check; if the length of the new array is different from X then this position does not occur and the frog can't cross the river to the other side.
Otherwise,  the function returns the position of X (B[B.Length-1]) in the original array, which is the one with the correct indexes (times).

PR


No comments:

Post a Comment