Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the first duplicate value in an array of ints between 1 and the n, with n being the size of the array?

/*
	This is an implementation that demonstrates
	how to efficiently find the first duplicate 
	value in an array of ints between 1 and n, 
	where n is the length of the array.
	
	Time complexity: O(n) 
	Space complexity: O(1)
*/
public class FirstDuplicateValue {
	public static void main(String[] args) {
		int[] arr = { 2, 1, 5, 3, 3, 2, 4 };
		// Below outputs: 3
		// as 3 is the first int appearing more
		// than once
		System.out.println(firstDuplicateValue(arr));
	}

	public static int firstDuplicateValue(int[] array) {
		// The main idea behind solution lies
		// in treating array elements as indices
		int index;
		for (int val : array) {
			index = Math.abs(val) - 1;
			if (array[index] < 0) {
				return index + 1;
			} else {
				array[index] *= -1;
			}
		}

		return -1;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: how to converet negative byte value to postive int value in java 
Java :: get player by name spigot 
Java :: check java version 
Java :: Date from String java3 
Java :: java one line if else 
Java :: how to compare 3 numbers in java 
Java :: spigot sounds 
Java :: circular list java 
Java :: java array contains 
Java :: java real random 
Java :: error: package androidx.multidex does not exist 
Java :: Which of the following is the only Java package that is imported by default? 
Java :: java max integer 
Java :: how to find power of a number in java 
Java :: how to solve simultaneous equations in mathematica 
Java :: change text color in joptionpane 
Java :: list in java 
Java :: java delete files 
Java :: get device id programmatically android 
Java :: java list to set 
Java :: java array loop backwards 
Java :: hibernate create query count return 
Java :: how to find a number in a string java 
Java :: json date format for localdate java 
Java :: java random char 
Java :: how to truncate decimals in java 
Java :: java filedialog 
Java :: android studio set text of textview 
Java :: java rps 
Java :: print * pattern in java 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =