Codility soloution for below code. I am getting wrong output. Can anyone tell me where I am wrong?

A zero- indexed array A consisting of N different integers is given. The array contains all integers in the range [0…N-1]. Sets S [K] for 0 ≤ K ≤ N are defines a s follows:
S[k] = {A[K], A[A[K]], A[A[A[K]]],….}.

Sets S[k] are finite for each k.

Write a function
Class Solution {public int solution (int a);}

That given an array A consisting of N integers, returns the size of the largest set S[K] for this array. The function should return O if the array is empty

For example A[0]=5, A[1]=4, A[2]=0, A[3]=3, A[4]=1, A[5]=6, A[6]=2,
The function should return 4, because set S [2] = {0, 5, 6, 2} has for elements. No other set S[k] has more than four elements

class Solution {
    public int solution(int[] A) {
        int max, count;
        max= count = 0;
        for (int i = 0; i < A.length; ++i) {
			count = 0;
			while (0 < A[i] && A[i] < A.length) {
				++count;
				int tmp = A[i];
				A[i] = 0;
			    i = tmp;
				max = Math.max(max, count);
			}
		}
		return max;
	}
	public static void main(String[] args) {
		Solution test = new Solution();
		System.out.println(test.solution(new int[]{5,4,0,3,1,6,2}));
	}
    }

Hi rajrules00007 welcome to the forum

I take it you are asking for help in demonstrating your coding skills to potential employers?

https://codility24.zendesk.com/hc/en-us/articles/203518472-Our-Story-and-What-We-re-About

Nothing personal, and leaving questions of ethics aside, the fact that you do not know that Java is not JavaScript suggests that you are wanting to be seen as being qualified for a position you are not qualified for. IMHO this could lead to nothing good.

Not that you should give up the idea of codility as a way to find employment. I’m not saying that at all.
What I am saying is that you should either seek employment where the skills that you do have will be appropriate, or take the time to learn the skills needed for a desired employment position.

@Mittineague c’mon, that might just as well be a typical university exercise. :-)

Anyway what strikes me is that you’re setting A[i] = 0 in the while-loop, thereby modifying the original input and falsifying the results of the following for-loops. You’ll have to find a better way to check if a given element was already visited, e.g. pushing to a temporary array. Also note that 0 < A[i] would exit the while loop even if the element actually is 0.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.