Given a sequence of  integers,  where each element is distinct and satisfies . For each  where , find any integer  such that  and print the value of  on a new line.
For example, assume the sequence . Each value of  between  and , the length of the sequence, is analyzed as follows:
  1. , so 
  2. , so 
  3. , so 
  4. , so 
  5. , so 
The values for  are .


Question from hackerrank.


Solution in C# - 


class Solution {

    static int[] permutationEquation(int[] p) {
        int n = p.Length;
        List<int> arr = new List<int>();
        for(int i=0; i<n; i++)
        {
            int x = i+1;
            int first_index = Array.IndexOf(p,x);
            int second_index = Array.IndexOf(p,first_index+1);
            arr.Add(second_index+1);
        }
        return arr.ToArray();
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());

        int[] p = Array.ConvertAll(Console.ReadLine().Split(' '), pTemp => Convert.ToInt32(pTemp));
        int[] result = permutationEquation(p);

        textWriter.WriteLine(string.Join("\n", result));

        textWriter.Flush();
        textWriter.Close();
    }

}

Post a Comment

Previous Post Next Post