HackerRank Larrys Array Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Larrys Array Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Larrys Array Solution
HackerRank Larrys Array Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Larrys Array

Task

Larry has been given a permutation of a sequence of natural numbers incrementing from 1 as an array. He must determine whether the array can be sorted using the following operation any number of times:

  • Choose any 3 consecutive indices and rotate their elements in such a way that ABC -> BCA -> CAB -> ABC.

For example, if A = {1, 6, 5, 2, 4, 3}:

A		rotate 
[1,6,5,2,4,3]	[6,5,2]
[1,5,2,6,4,3]	[5,2,6]
[1,2,6,5,4,3]	[5,4,3]
[1,2,6,3,5,4]	[6,3,5]
[1,2,3,5,6,4]	[5,6,4]
[1,2,3,4,5,6]

YES

On a new line for each test case, print YES if  can be fully sorted. Otherwise, print NO.

Function Description

Complete the larrysArray function in the editor below. It must return a string, either YES or NO.

larrysArray has the following parameter(s):

  • A: an array of integers

Input Format

The first line contains an integer t, the number of test cases.

The next t pairs of lines are as follows:

  • The first line contains an integer n, the length of A.
  • The next line contains n space-separated integers A[i].

Constraints

  • 1 <= t <= 10
  • 3 <= n <= 1000
  • 1 <= A[i] <= n
  • Asorted = integers that increment by 1 from 1 to n

Output Format

For each test case, print YES if A can be fully sorted. Otherwise, print NO.

Sample Input

3
3
3 1 2
4
1 3 4 2
5
1 2 3 5 4

Sample Output

YES
YES
NO

Explanation

In the explanation below, the subscript of A denotes the number of operations performed.

Test Case 0:
A0 = {3, 1, 2} -> rotate(3, 1, 2) -> A1 = {1, 2, 3}
A is now sorted, so we print YES on a new line.

Test Case 1:
A0 = {1, 3, 4, 2} -> rotate(3, 4, 2) -> A1 = {1, 4, 2, 3}.
A1 = {1, 4, 2, 3} -> rotate(4, 2, 3) -> A2 = {1, 2, 3, 4}.
A is now sorted, so we print YES on a new line.

Test Case 2:
No sequence of rotations will result in a sorted A. Thus, we print NO on a new line.

HackerRank Larrys Array Solution

Larrys Array Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    unsigned t;
    scanf ("%u", &t);

    while (t--) {
        unsigned n;
        scanf ("%u", &n);

        unsigned a[n];
        for (unsigned i = 0; i < n; i++) {
            scanf ("%u", a + i);
        }

        unsigned int num_inv = 0;
        for (unsigned i = 0; i < n ; i++) {
            for (unsigned j = i + 1; j < n; j++) {
                if (a[i] > a[j]) {
                    num_inv++;
                }
            }
        }
        if (num_inv % 2) {
            printf ("NO\n");
        } else {
            printf ("YES\n");
        }
    }
    return 0;
}

Larrys Array Solution in Cpp

#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#include <limits>
#include <functional>
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#if defined(_MSC_VER) || __cplusplus > 199711L
#define aut(r,v) auto r = (v)
#else
#define aut(r,v) __typeof(v) r = (v)
#endif
#define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it)
#define all(o) (o).begin(), (o).end()
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define mset(m,v) memset(m,v,sizeof(m))
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pair<int, int> > vpii; typedef long long ll;
template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

int main() {
	int T;
	scanf("%d", &T);
	for(int ii = 0; ii < T; ++ ii) {
		int N;
		scanf("%d", &N);
		vector<int> A(N);
		for(int i = 0; i < N; ++ i)
			scanf("%d", &A[i]);
		int p = 0;
		rep(i, N) rep(j, i)
			p += A[i] < A[j];
		bool ans = p % 2 == 0;
		puts(ans ? "YES" : "NO");
	}
	return 0;
}

Larrys Array Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        int n;
        List<Integer> a;
        for (int i = 0; i < t; i++) {
            n = in.nextInt();
            a = new ArrayList<Integer>(n);
            for (int j = 0; j < n; j++) {
                a.add(in.nextInt());
            }
            for (int curElem = 1; curElem <= n - 2; curElem++) {
                int curIdx = a.indexOf(curElem);
                System.err.println(a);
                while (curIdx != curElem - 1) {
                    if (curIdx == a.size() - 1) {
                        int tmp = a.get(curIdx - 2);
                        a.set(curIdx - 2, a.get(curIdx - 1));
                        a.set(curIdx - 1, curElem);
                        a.set(curIdx, tmp);
                    } else {
                        int tmp = a.get(curIdx - 1);
                        a.set(curIdx - 1, curElem);
                        a.set(curIdx, a.get(curIdx + 1));
                        a.set(curIdx + 1, tmp);
                    }
                    curIdx--;
                }
            }
            System.err.println(a);
            boolean printed = false;
            for (int j = 1; j < a.size(); j++) {
                if (a.get(j) < a.get(j-1)) {
                    System.out.println("NO");
                    printed = true;
                }
            }
            if (!printed) System.out.println("YES");
        }        
    }
}

Larrys Array Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
x=int(raw_input())

for _ in range(x):
    raw_input()
    arr=[int(i) for i in raw_input().split()]
    count=0
    for ind,val in enumerate(arr):
        count+=sum(i>val for i in arr[:ind])
    if count%2==0:
        print "YES"
    else:
        print "NO"

Larrys Array Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var T = +readLine();
    
    while(T--) {
        var N = +readLine();
        var P = readLine().split(' ');
        
        var C = 0,i,j,t;

        
        //console.log('>>',P);
        
        for(i=0;i<P.length;i++) {
            if (P[i]!=i+1) {
                for(j=i+1;j<P.length;j++) if (P[j]==i+1) {
                    break;
                };
                while(j>i) {
                    t = P[j-1];
                    P[j-1] = P[j];
                    P[j] = t;
                    //console.log(P);
                    j--;
                    C++;
                };
            };
        };
        
        //console.log('--',C);
        if (C%2==0) {
            console.log('YES');
        } else {
            console.log('NO');
        }
        
    };
    
}

Larrys Array Solution in Scala

object Solution {

  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val t = sc.nextInt()
    for (_ <- 1 to t) {
      val n = sc.nextInt
      val ar = (1 to n).map(_ => sc.nextInt())
      if (isSolvable(ar.toList)) {
        println("YES")
      } else {
        println("NO")
      }
    }
  }

  def isSolvable(ar: List[Int]):Boolean = {
    ar.tails.filter(_.length > 1).map({
      case h::t => t.count(_ < h)
      case _ => 0
    }).sum % 2 == 0
  }

}

Larrys Array Solution in Pascal

type
    TArr = array of integer;
var
    Tests, i: integer;
    a: TArr;
    n, j, k, temp, Start, Min: integer;

function MinN: integer;
var
  i: integer;
begin
  MinN := start+1;
  for i := Start +1 to n-1 do
    if a[i] < a[MinN] then MinN := i;
end;

function Sort: boolean;
var
  i: integer;
begin
  Sort := true;
  for i := 0 to n-2 do
    if a[i] > a[i+1] then Sort := false;
end;

begin
    readln(Tests);
    for i := 1 to Tests do
        begin
            readln(n);
            SetLength(a, n);
            for j := 0 to n-1 do
                read(a[j]);
                
            // 2 1 0 3
            // Находим минимальный элемент
            k := 0;
            Start := -1;
            Min := MinN;  
            while (start < n-3)do
              begin               
                  
                
                {
                k := k + 1;
                if k > n-start then break;
                }
                
                if Min = Start +1 then
                  begin
                    start := start + 1;
                    Min := MinN; 
                    k := 0;
                  end
                else
                  begin
                    if min < n-1 then
                      begin
                        temp := a[min-1];
                        a[min-1] := a[min];
                        a[min] := a[min+1];
                        a[min+1] := temp;
                        Min := Min - 1;
                      end
                    else
                      begin
                        temp := a[min-2];
                        a[min-2] := a[min];
                        a[min] := a[min-1];
                        a[min-1] := temp;
                        Min := Min-2;
                      end;
                  end;
              end;
            if Sort then writeln('YES') else writeln('NO');
        end;
end.

Disclaimer: This problem (Larrys Array) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment