Finding the second smallest integer in array - java

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.
Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.
Below is my code, so far:
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = 0;
int secondSmallest = 0;
for (int i = 0; i < elements.length; i++)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[i] < smallest)
{
smallest = elements[i];
if (elements[j] < secondSmallest)
{
secondSmallest = elements[j];
}
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
This works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.
Array rearrangements are forbidden.

Try this one. Second condition is used to catch an event when the smallest number is the first
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if(elements[i]==smallest){
secondSmallest=smallest;
} else if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
UPD by #Axel
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}

Here is TimeComlexity Linear O(N):
public static int secondSmallest(int[] arr) {
if(arr==null || arr.length < 2) {
throw new IllegalArgumentException("Input array too small");
}
//implement
int firstSmall = -1;
int secondSmall = -1;
//traverse to find 1st small integer on array
for (int i = 0; i<arr.length;i++)
if (firstSmall == -1 || arr[firstSmall]>arr[i])
firstSmall = i;
//traverse to array find 2 integer, and skip first small
for (int i = 0;i<arr.length;i++) {
if (i != firstSmall && (secondSmall == -1 || arr[secondSmall] > arr[i]))
secondSmall = i;
}
return arr[secondSmall];
}

int[] arr = { 4, 1, 2, 0, 6, 1, 2, 0 };
int smallest = Integer.MAX_VALUE;
int smaller = Integer.MAX_VALUE;
int i = 0;
if (arr.length > 2) {
for (i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smaller = smallest;
smallest = arr[i];
} else if (arr[i] < smaller && arr[i] > smallest) {
smaller = arr[i];
}
}
System.out.println("Smallest number is " + smallest);
System.out.println("Smaller number is " + smaller);
} else {
System.out.println("Invalid array !");
}
}

You can do it in O(n) time. Below is the python code
def second_small(A):
if len(A)<2:
print 'Invalid Array...'
return
small = A[0]
second_small = [1]
if small > A[1]:
second_small,small = A[0],A[1]
for i in range(2,len(A)):
if A[i] < second_small and A[i]!=small:
if A[i] < small:
second_small = small
small = A[i]
else:
second_small = A[i]
print small, second_small
A = [12, 13, 1, 10, 34, 1]
second_small(A)

public static int findSecondSmallest(int[] elements) {
if (elements == null || elements.length < 2) {
throw new IllegalArgumentException();
}
int smallest = elements[0];
int secondSmallest = elements[0];
for (int i = 1; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
}
else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
return secondSmallest;
}

Simply, you can do this
int[] arr = new int[]{34, 45, 21, 12, 54, 67, 15};
Arrays.sort(arr);
System.out.println(arr[1]);

Try this one.
public static void main(String args[]){
int[] array = new int[]{10, 30, 15, 8, 20, 4};
int min, secondMin;
if (array[0] > array[1]){
min = array[1];
secondMin = array[0];
}
else{
min = array[0];
secondMin = array[1];
}
for (int i=2; i<array.length; i++){
if (array[i] < min){
secondMin = min;
min = array[i];
}
else if ((array[i] > min) && (array[i] < secondMin)){
secondMin = array[i];
}
}
System.out.println(secondMin);
}

I've used Sort function in javascript
function sumTwoSmallestNumbers(numbers){
numbers = numbers.sort(function(a, b){return a - b; });
return numbers[0] + numbers[1];
};
by providing a compareFunction for the sort functionality array elements are sorted according to the return value of the function.

How about this?
int[] result = Arrays.asList(-3, 4,-1,-2).stream()
.reduce(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE},
(maxValues, x) -> {
if (x > maxValues[0]) {
maxValues[1] = maxValues[0]; //max becomes second max
maxValues[0] = x;
}
else if (x > maxValues[1]) maxValues[1] = x;
return maxValues;
}
, (x, y) -> x);

class A{
public static void main (String args[]){
int array[]= {-5, -4, 0, 2, 10, 3, -3};
int min;
int second_min;
if(array[0]<array[1]){
min=array[0];
second_min=array[1];
}else{
min=array[1];
second_min=array[0];
}
for(int i=2;i<array.length;i++){
if(second_min > array[i] && min > array[i]){
second_min=min;
min=array[i];
}else if(second_min > array[i] && min < array[i]){
min=min;
second_min=array[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}

Find the second minimum element of an array in Python, short and simple
def second_minimum(arr):
second = arr[1]
first = arr[0]
for n in arr:
if n < first:
first = n
if n > first and n < second :
second = n
return second
print(second_minimum([-2, 4, 5, -1, 2, 3, 0, -4, 1, 99, -6, -5, -19]))

public static void main(String[] args)
{
int[] elements = {-4 , 2 , 10 , -2, -3 };
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++)
{
if (smallest>elements[i])
smallest=elements[i];
}
for (int i = 0; i < elements.length; i++)
{
if (secondSmallest>elements[i] && elements[i]>smallest)
secondSmallest=elements[i];
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter array size = ");
int size=in.nextInt();
int[] n = new int[size];
System.out.println("Enter "+ size +" values ");
for(int i=0;i<n.length;i++)
n[i] = in.nextInt();
int small=n[0],ssmall=n[0];
// finding small and second small
for(int i=0;i<n.length;i++){
if(small>n[i]){
ssmall=small;
small=n[i];
}else if(ssmall>n[i])
ssmall=n[i];
}
// finding second small if first element itself small
if(small==n[0]){
ssmall=n[1];
for(int i=1;i<n.length;i++){
if(ssmall>n[i]){
ssmall=n[i];
}
}
}
System.out.println("Small "+ small+" sSmall "+ ssmall);
in.close();
}

public static void main(String[] args) {
int arr[] = {6,1,37,-4,12,46,5,64,21,2,-4,-3};
int lowest =arr[0];
int sec_lowest =arr[0];
for(int n : arr){
if (lowest > n)
{
sec_lowest = lowest;
lowest = n;
}
else if (sec_lowest > n && lowest != n)
sec_lowest = n;
}
System.out.println(lowest+" "+sec_lowest);
}

public class SecondSmallestNumberInArray
{
public static void main(String[] args)
{
int arr[] = { 99, 76, 47, 85, 929, 52, 48, 36, 66, 81, 9 };
int smallest = arr[0];
int secondSmallest = arr[0];
System.out.println("The given array is:");
boolean find = false;
boolean flag = true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println("");
while (flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < smallest)
{
find = true;
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest) {
find = true;
secondSmallest = arr[i];
}
}
if (find) {
System.out.println("\nSecond Smallest number is Array : -> " + secondSmallest);
flag = false;
} else {
smallest = arr[1];
secondSmallest = arr[1];
}
}
}
}
**Output is**
D:\Java>java SecondSmallestNumberInArray
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second Smallest number is Array : -> 36
D:\Java>

public static int getSecondSmallest(int[] arr){
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(smallest > arr[i]){
secondSmallest = smallest;
smallest = arr[i];
}else if (secondSmallest > arr[i] && arr[i] != smallest){
secondSmallest = arr[i];
}
System.out.println(i+" "+smallest+" "+secondSmallest);
}
return secondSmallest;
}
Just gave it a try with some of the test cases and it worked. Please check if it is correct!

Try this ...
First condition checks if both values are less than value in array.
Second condition if value is less than small than smallest=element[i]
else secondSmallest=elements[i]..
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = elements[0];
int secondSmallest = 0;
for (int i = 0; i < elements.Length; i++)
{
if (elements[i]<smallest || elements[i]<secondSmallest )
{
if (elements[i] < smallest )
{
secondSmallest = smallest ;
smallest = elements[i];
}
else
{
secondSmallest = elements[i];
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}

Try this, program gives solution for both lowest value and second lowest value of array.
Initialize min and second_min with first element of array.Find out the min value and compare it with second_min value . If it (second_min) is greater than current element of array and min value then the second_min value replace with current element of array.
In case arr[]={2,6,12,15,11,0,3} like this , temp variable used to store previous second_min value.
public class Main
{
public static void main(String[] args) {
//test cases.
int arr[]={6,12,1,11,0};
//int arr[]={0,2,10,3,-3};
//int arr[]={0,0,10,3,-3};
//int arr[]={0,2 ,10, 3,-3};
//int arr[]={12,13,1,10,34,1};
//int arr[]={2,6,12,15,11,0,3};
//int arr[]={2,6,12,15,1,0,3};
//int arr[]={2,6,12,15};
//int arr[]={0,1};
//int arr[]={6,16};
//int arr[]={12};
//int arr[]={6,6,6,6,6,6};
int position_min=0;
int min=arr[0];int second_min=arr[0]; int temp=arr[0];
if(arr.length==1)
{
System.out.println("Lowest value is "+arr[0]+"\n Array length should be greater than 1. ");
}
else if(arr.length==2)
{
if(arr[0]>arr[1])
{
min=arr[1];
second_min=arr[0];
position_min=1;
}
else
{
min=arr[0];
second_min=arr[1];
position_min=0;
}
System.out.println("Lowest value is "+min+"\nSecond lowest value is "+second_min);
}
else
{
for( int i=1;i<arr.length;i++)
{
if(min>arr[i])
{
min=arr[i];
position_min=i;
}
}
System.out.println("Lowest value is "+min);
for(int i=1;i<arr.length;i++)
{
if(position_min==i)
{
}
else
{
if(second_min > min & second_min>arr[i])
{
temp=second_min;
second_min=arr[i];
}
else if(second_min == min )
{
second_min=arr[i];
}
}
}
if(second_min==min )
{
second_min=temp;
}
//just for message if in case all elements are same in array.
if(temp==min && second_min==min)
{
System.out.println("There is no Second lowest element in array.");
}
else{
System.out.println("\nSecond lowest value is "+second_min);
}
}
}
}

Here's a Swift version that runs in linear time. Basically, find the smallest number. Then assign the 2nd minimum number as the largest value. Then loop through through the array and find a number greater than the smallest one but also smaller than the 2nd smallest found so far.
func findSecondMinimumElementLinear(in nums: [Int]) -> Int? {
// If the size is less than 2, then returl nil.
guard nums.count > 1 else { return nil }
// First, convert it into a set to reduce duplicates.
let uniqueNums = Array(Set(nums))
// There is no point in sorting if all the elements were the same since it will only leave 1 element
// after the set removed duplicates.
if uniqueNums.count == 1 { return nil }
let min: Int = uniqueNums.min() ?? 0 // O(n)
var secondMinNum: Int = uniqueNums.max() ?? 0 // O(n)
// O(n)
for num in uniqueNums {
if num > min && num < secondMinNum {
secondMinNum = num
}
}
return secondMinNum
}

a straight forward solution in lambda
int[] first = {Integer.MAX_VALUE};
int rslt = IntStream.of( elements ).sorted().dropWhile( n -> {
boolean b = n == first[0] || first[0] == Integer.MAX_VALUE;
first[0] = n;
return( b );
} ).findFirst().orElse( Integer.MAX_VALUE );
the returned OptionalInt from findFirst() can be used to handle the special cases
for elements.length < 2 or elements containing only one value several times
here Integer.MAX_VALUE is returned, if there is no second smallest integer

Well, that should work for you:
function getSecondMin(array){
if(array.length < 2) return NaN;
let min = Math.min(array[0],array[1]);
let secondMin = Math.max(array[0],array[1])
for (let i = 2; i < array.length; i++) {
if(array[i]< min){
secondMin = min
min = array[i]
}
else if(array[i] < secondMin){
secondMin = array[i]
}
}
return secondMin;
}
const secondMin = getSecondMin([1,4,3,100,2])
console.log(secondMin || "invalid array length");

Related

Given an array of arrays, for each inner array - If the array has < 2 numbers, return 0 else return second smallest number [duplicate]

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.
Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.
Below is my code, so far:
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = 0;
int secondSmallest = 0;
for (int i = 0; i < elements.length; i++)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[i] < smallest)
{
smallest = elements[i];
if (elements[j] < secondSmallest)
{
secondSmallest = elements[j];
}
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
This works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.
Array rearrangements are forbidden.
Try this one. Second condition is used to catch an event when the smallest number is the first
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if(elements[i]==smallest){
secondSmallest=smallest;
} else if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
UPD by #Axel
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
Here is TimeComlexity Linear O(N):
public static int secondSmallest(int[] arr) {
if(arr==null || arr.length < 2) {
throw new IllegalArgumentException("Input array too small");
}
//implement
int firstSmall = -1;
int secondSmall = -1;
//traverse to find 1st small integer on array
for (int i = 0; i<arr.length;i++)
if (firstSmall == -1 || arr[firstSmall]>arr[i])
firstSmall = i;
//traverse to array find 2 integer, and skip first small
for (int i = 0;i<arr.length;i++) {
if (i != firstSmall && (secondSmall == -1 || arr[secondSmall] > arr[i]))
secondSmall = i;
}
return arr[secondSmall];
}
int[] arr = { 4, 1, 2, 0, 6, 1, 2, 0 };
int smallest = Integer.MAX_VALUE;
int smaller = Integer.MAX_VALUE;
int i = 0;
if (arr.length > 2) {
for (i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smaller = smallest;
smallest = arr[i];
} else if (arr[i] < smaller && arr[i] > smallest) {
smaller = arr[i];
}
}
System.out.println("Smallest number is " + smallest);
System.out.println("Smaller number is " + smaller);
} else {
System.out.println("Invalid array !");
}
}
You can do it in O(n) time. Below is the python code
def second_small(A):
if len(A)<2:
print 'Invalid Array...'
return
small = A[0]
second_small = [1]
if small > A[1]:
second_small,small = A[0],A[1]
for i in range(2,len(A)):
if A[i] < second_small and A[i]!=small:
if A[i] < small:
second_small = small
small = A[i]
else:
second_small = A[i]
print small, second_small
A = [12, 13, 1, 10, 34, 1]
second_small(A)
public static int findSecondSmallest(int[] elements) {
if (elements == null || elements.length < 2) {
throw new IllegalArgumentException();
}
int smallest = elements[0];
int secondSmallest = elements[0];
for (int i = 1; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
}
else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
return secondSmallest;
}
Simply, you can do this
int[] arr = new int[]{34, 45, 21, 12, 54, 67, 15};
Arrays.sort(arr);
System.out.println(arr[1]);
Try this one.
public static void main(String args[]){
int[] array = new int[]{10, 30, 15, 8, 20, 4};
int min, secondMin;
if (array[0] > array[1]){
min = array[1];
secondMin = array[0];
}
else{
min = array[0];
secondMin = array[1];
}
for (int i=2; i<array.length; i++){
if (array[i] < min){
secondMin = min;
min = array[i];
}
else if ((array[i] > min) && (array[i] < secondMin)){
secondMin = array[i];
}
}
System.out.println(secondMin);
}
I've used Sort function in javascript
function sumTwoSmallestNumbers(numbers){
numbers = numbers.sort(function(a, b){return a - b; });
return numbers[0] + numbers[1];
};
by providing a compareFunction for the sort functionality array elements are sorted according to the return value of the function.
How about this?
int[] result = Arrays.asList(-3, 4,-1,-2).stream()
.reduce(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE},
(maxValues, x) -> {
if (x > maxValues[0]) {
maxValues[1] = maxValues[0]; //max becomes second max
maxValues[0] = x;
}
else if (x > maxValues[1]) maxValues[1] = x;
return maxValues;
}
, (x, y) -> x);
class A{
public static void main (String args[]){
int array[]= {-5, -4, 0, 2, 10, 3, -3};
int min;
int second_min;
if(array[0]<array[1]){
min=array[0];
second_min=array[1];
}else{
min=array[1];
second_min=array[0];
}
for(int i=2;i<array.length;i++){
if(second_min > array[i] && min > array[i]){
second_min=min;
min=array[i];
}else if(second_min > array[i] && min < array[i]){
min=min;
second_min=array[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}
Find the second minimum element of an array in Python, short and simple
def second_minimum(arr):
second = arr[1]
first = arr[0]
for n in arr:
if n < first:
first = n
if n > first and n < second :
second = n
return second
print(second_minimum([-2, 4, 5, -1, 2, 3, 0, -4, 1, 99, -6, -5, -19]))
public static void main(String[] args)
{
int[] elements = {-4 , 2 , 10 , -2, -3 };
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++)
{
if (smallest>elements[i])
smallest=elements[i];
}
for (int i = 0; i < elements.length; i++)
{
if (secondSmallest>elements[i] && elements[i]>smallest)
secondSmallest=elements[i];
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter array size = ");
int size=in.nextInt();
int[] n = new int[size];
System.out.println("Enter "+ size +" values ");
for(int i=0;i<n.length;i++)
n[i] = in.nextInt();
int small=n[0],ssmall=n[0];
// finding small and second small
for(int i=0;i<n.length;i++){
if(small>n[i]){
ssmall=small;
small=n[i];
}else if(ssmall>n[i])
ssmall=n[i];
}
// finding second small if first element itself small
if(small==n[0]){
ssmall=n[1];
for(int i=1;i<n.length;i++){
if(ssmall>n[i]){
ssmall=n[i];
}
}
}
System.out.println("Small "+ small+" sSmall "+ ssmall);
in.close();
}
public static void main(String[] args) {
int arr[] = {6,1,37,-4,12,46,5,64,21,2,-4,-3};
int lowest =arr[0];
int sec_lowest =arr[0];
for(int n : arr){
if (lowest > n)
{
sec_lowest = lowest;
lowest = n;
}
else if (sec_lowest > n && lowest != n)
sec_lowest = n;
}
System.out.println(lowest+" "+sec_lowest);
}
public class SecondSmallestNumberInArray
{
public static void main(String[] args)
{
int arr[] = { 99, 76, 47, 85, 929, 52, 48, 36, 66, 81, 9 };
int smallest = arr[0];
int secondSmallest = arr[0];
System.out.println("The given array is:");
boolean find = false;
boolean flag = true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println("");
while (flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < smallest)
{
find = true;
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest) {
find = true;
secondSmallest = arr[i];
}
}
if (find) {
System.out.println("\nSecond Smallest number is Array : -> " + secondSmallest);
flag = false;
} else {
smallest = arr[1];
secondSmallest = arr[1];
}
}
}
}
**Output is**
D:\Java>java SecondSmallestNumberInArray
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second Smallest number is Array : -> 36
D:\Java>
public static int getSecondSmallest(int[] arr){
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(smallest > arr[i]){
secondSmallest = smallest;
smallest = arr[i];
}else if (secondSmallest > arr[i] && arr[i] != smallest){
secondSmallest = arr[i];
}
System.out.println(i+" "+smallest+" "+secondSmallest);
}
return secondSmallest;
}
Just gave it a try with some of the test cases and it worked. Please check if it is correct!
Try this ...
First condition checks if both values are less than value in array.
Second condition if value is less than small than smallest=element[i]
else secondSmallest=elements[i]..
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = elements[0];
int secondSmallest = 0;
for (int i = 0; i < elements.Length; i++)
{
if (elements[i]<smallest || elements[i]<secondSmallest )
{
if (elements[i] < smallest )
{
secondSmallest = smallest ;
smallest = elements[i];
}
else
{
secondSmallest = elements[i];
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
Try this, program gives solution for both lowest value and second lowest value of array.
Initialize min and second_min with first element of array.Find out the min value and compare it with second_min value . If it (second_min) is greater than current element of array and min value then the second_min value replace with current element of array.
In case arr[]={2,6,12,15,11,0,3} like this , temp variable used to store previous second_min value.
public class Main
{
public static void main(String[] args) {
//test cases.
int arr[]={6,12,1,11,0};
//int arr[]={0,2,10,3,-3};
//int arr[]={0,0,10,3,-3};
//int arr[]={0,2 ,10, 3,-3};
//int arr[]={12,13,1,10,34,1};
//int arr[]={2,6,12,15,11,0,3};
//int arr[]={2,6,12,15,1,0,3};
//int arr[]={2,6,12,15};
//int arr[]={0,1};
//int arr[]={6,16};
//int arr[]={12};
//int arr[]={6,6,6,6,6,6};
int position_min=0;
int min=arr[0];int second_min=arr[0]; int temp=arr[0];
if(arr.length==1)
{
System.out.println("Lowest value is "+arr[0]+"\n Array length should be greater than 1. ");
}
else if(arr.length==2)
{
if(arr[0]>arr[1])
{
min=arr[1];
second_min=arr[0];
position_min=1;
}
else
{
min=arr[0];
second_min=arr[1];
position_min=0;
}
System.out.println("Lowest value is "+min+"\nSecond lowest value is "+second_min);
}
else
{
for( int i=1;i<arr.length;i++)
{
if(min>arr[i])
{
min=arr[i];
position_min=i;
}
}
System.out.println("Lowest value is "+min);
for(int i=1;i<arr.length;i++)
{
if(position_min==i)
{
}
else
{
if(second_min > min & second_min>arr[i])
{
temp=second_min;
second_min=arr[i];
}
else if(second_min == min )
{
second_min=arr[i];
}
}
}
if(second_min==min )
{
second_min=temp;
}
//just for message if in case all elements are same in array.
if(temp==min && second_min==min)
{
System.out.println("There is no Second lowest element in array.");
}
else{
System.out.println("\nSecond lowest value is "+second_min);
}
}
}
}
Here's a Swift version that runs in linear time. Basically, find the smallest number. Then assign the 2nd minimum number as the largest value. Then loop through through the array and find a number greater than the smallest one but also smaller than the 2nd smallest found so far.
func findSecondMinimumElementLinear(in nums: [Int]) -> Int? {
// If the size is less than 2, then returl nil.
guard nums.count > 1 else { return nil }
// First, convert it into a set to reduce duplicates.
let uniqueNums = Array(Set(nums))
// There is no point in sorting if all the elements were the same since it will only leave 1 element
// after the set removed duplicates.
if uniqueNums.count == 1 { return nil }
let min: Int = uniqueNums.min() ?? 0 // O(n)
var secondMinNum: Int = uniqueNums.max() ?? 0 // O(n)
// O(n)
for num in uniqueNums {
if num > min && num < secondMinNum {
secondMinNum = num
}
}
return secondMinNum
}
a straight forward solution in lambda
int[] first = {Integer.MAX_VALUE};
int rslt = IntStream.of( elements ).sorted().dropWhile( n -> {
boolean b = n == first[0] || first[0] == Integer.MAX_VALUE;
first[0] = n;
return( b );
} ).findFirst().orElse( Integer.MAX_VALUE );
the returned OptionalInt from findFirst() can be used to handle the special cases
for elements.length < 2 or elements containing only one value several times
here Integer.MAX_VALUE is returned, if there is no second smallest integer
Well, that should work for you:
function getSecondMin(array){
if(array.length < 2) return NaN;
let min = Math.min(array[0],array[1]);
let secondMin = Math.max(array[0],array[1])
for (let i = 2; i < array.length; i++) {
if(array[i]< min){
secondMin = min
min = array[i]
}
else if(array[i] < secondMin){
secondMin = array[i]
}
}
return secondMin;
}
const secondMin = getSecondMin([1,4,3,100,2])
console.log(secondMin || "invalid array length");

move all even numbers on the first half and odd numbers to the second half in an integer array

I had an interview question which i could not solve.
Write method (not a program) in Java Programming Language that will move all even numbers on the first half and odd numbers to the second half in an integer array.
E.g. Input = {3,8,12,5,9,21,6,10}; Output = {12,8,6,10,3,5,9,21}.
The method should take integer array as parameter and move items in the same array (do not create another array). The numbers may be in different order than original array. This is algorithm test, so try to give as efficient algorithm as you can (possibly linear O(n) algorithm). Avoid using built in functions/API. *
Also some basic intro to what is data structure efficiency
Keep two indices: one to the first odd number and one to the last even number. Swap such numbers and update indices.
(With a lot of help from #manu-fatto's suggestion) I believe this would do it:
private static int[] OddSort(int[] items)
{
int oddPos, nextEvenPos;
for (nextEvenPos = 0;
nextEvenPos < items.Length && items[nextEvenPos] % 2 == 0;
nextEvenPos++) { }
// nextEvenPos is now positioned at the first odd number in the array,
// i.e. it is the next place an even number will be placed
// We already know that items[nextEvenPos] is odd (from the condition of the
// first loop), so we'll start looking for even numbers at nextEvenPos + 1
for (oddPos = nextEvenPos + 1; oddPos < items.Length; oddPos++)
{
// If we find an even number
if (items[oddPos] % 2 == 0)
{
// Swap the values
int temp = items[nextEvenPos];
items[nextEvenPos] = items[oddPos];
items[oddPos] = temp;
// And increment the location for the next even number
nextEvenPos++;
}
}
return items;
}
This algorithm traverses the list exactly 1 time (inspects each element exactly once), so the efficiency is O(n).
// to do this in one for loop
public static void evenodd(int[] integer) {
int i = 0, temp = 0;
int j = integer.length - 1;
while (j >= i) {
// swap if found odd even combo at i and j
if (integer[i] % 2 != 0 && integer[j] % 2 == 0) {
temp = integer[i];
integer[i] = integer[j];
integer[j] = temp;
i++;
j--;
} else {
if (integer[i] % 2 == 0) {
i++;
}
if (integer[j] % 2 == 1) {
j--;
}
}
}
}
#JLRishe,
Your algorithm doesn't maintain the order. For a simple example, say {1,5,2}, you will change the array to {2,5,1}. I could not comment below your post as I am a new user and lack reputations.
public static void sorted(int [] integer) {
int i, j , temp;
for (i = 0; i < integer.length; i++) {
if (integer[i] % 2 == 0) {
for (j = i; j < integer.length; j++) {
if (integer[j] % 2 == 1) {
temp = y[i];
y[i] = y[j];
y[j] = temp;
}
}
}
System.out.println(integer[i]);
}
public static void main(String args[]) {
sorted(new int[]{1, 2,7, 9, 4});
}
}
The answer is 1, 7, 9, 2, 4.
Could it be that you were asked to implement a very basic version of the BubbleSort where the sort value of element e, where e = arr[i], = e%2==1 ? 1 : -1 ?
Regards
Leon
class Demo
{
public void sortArray(int[] a)
{
int len=a.length;
int j=len-1;
for(int i=0;i<len/2+1;i++)
{
if(a[i]%2!=0)
{
while(a[j]%2!=0 && j>(len/2)-1)
j--;
if(j<=(len/2)-1)
break;
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
for(int i=0;i<len;i++)
System.out.println(a[i]);
}
public static void main(String s[])
{
int a[]=new int[10];
System.out.println("Enter 10 numbers");
java.util.Scanner sc=new java.util.Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
new Demo().sortArray(a);
}
}
private static void rearrange(int[] a) {
int i,j,temp;
for(i = 0, j = a.length - 1; i < j ;i++,j--) {
while(a[i]%2 == 0 && i != a.length - 1) {
i++;
}
while(a[j]%2 == 1 && j != 0) {
j--;
}
if(i>j)
break;
else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
public void sortEvenOddIntegerArray(int[] intArray){
boolean loopRequired = false;
do{
loopRequired = false;
for(int i = 0;i<intArray.length-1;i++){
if(intArray[i] % 2 != 0 && intArray[i+1] % 2 == 0){
int temp = intArray[i];
intArray[i] = intArray[i+1];
intArray[i+1] = temp;
loopRequired = true;
}
}
}while(loopRequired);
}
You can do this with a single loop by moving odd items to the end of the array when you find them.
static void EvensToLeft(int[] items) {
int end = items.length;
for (int i = 0; i < end; i++) {
if (items[i] % 2) {
int t = items[i];
items[i--] = items[--end];
items[end] = t;
}
}
}
Given an input array of length n the inner loop executes exactly n times, and computes the parity of each array element exactly once.
Use two counters i=0 and j=a.length-1 and keep swapping even and odd elements that are in the wrong place.
public int[] evenOddSort(int[] a) {
int i = 0;
int j = a.length - 1;
int temp;
while (i < j) {
if (a[i] % 2 == 0) {
i++;
} else if (a[j] % 2 != 0) {
j--;
} else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
return a;
}
public class SeperatOddAndEvenInList {
public static int[] seperatOddAndEvnNos(int[] listOfNumbers) {
int oddNumPointer = 0;
int evenNumPointer = listOfNumbers.length - 1;
while(oddNumPointer <= evenNumPointer) {
if(listOfNumbers[oddNumPointer] % 2 == 0) { //even number, swap to front of last known even number
int temp;
temp = listOfNumbers[oddNumPointer];
listOfNumbers[oddNumPointer] = listOfNumbers[evenNumPointer];
listOfNumbers[evenNumPointer] = temp;
evenNumPointer--;
}
else { //odd number, go ahead... capture next element
oddNumPointer++;
}
}
return listOfNumbers;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int []arr = {3, 8, 12, 5, 9, 21, 6, 10};
int[] seperatedArray = seperatOddAndEvnNos(arr);
for (int i : seperatedArray) {
System.out.println(i);
}
}
}
public class ArraysSortEvensFirst {
public static void main(String[] args) {
int[] arr = generateTestData();
System.out.println(Arrays.toString(arr));
ArraysSortEvensFirst test = new ArraysSortEvensFirst();
test.sortEvensFirst(arr);
}
private static int[] generateTestData() {
int[] arr = {1,3,5,6,9,2,4,5,7};
return arr;
}
public int[] sortEvensFirst(int[] arr) {
int end = arr.length;
int last = arr.length-1;
for(int i=0; i < arr.length; i++) {
// find odd elements, then move to even slots
if(arr[i]%2 > 0) {
int k = findEven(last, arr);
if(k > i) swap(arr, i, k);
last = k;
}
}
System.out.println(Arrays.toString(arr));
return arr;
}
public int findEven(int last, int[] arr) {
for(int k = last; k > 0; k--) {
if(arr[k]%2 == 0) {
return k;
}
}
return -1; // not found;
}
public void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
Output:
[1, 3, 5, 6, 9, 2, 4, 5, 7]
[4, 2, 6, 5, 9, 3, 1, 5, 7]
efficiency is O(log n).
public class TestProg {
public static void main(String[] args) {
int[] input = { 32, 54, 35, 18, 23, 17, 2 };
int front = 0;
int mid = input.length - 1;
for (int start = 0; start < input.length; start++) {
//if current element is odd
if (start < mid && input[start] % 2 == 1) {
//swapping element is also odd?
if (input[mid] % 2 == 1) {
mid--;
start--;
}
//swapping element is not odd then swap
else {
int tmp = input[mid];
input[mid] = input[start];
input[start] = tmp;
mid--;
}
}
}
for (int x : input)
System.out.print(x + " ");
}
}

finding the start and end index for a max sub array

public static void main(String[] args) {
int arr[]= {0,-1,2,-3,5,9,-5,10};
int max_ending_here=0;
int max_so_far=0;
int start =0;
int end=0;
for(int i=0;i< arr.length;i++)
{
max_ending_here=max_ending_here+arr[i];
if(max_ending_here<0)
{
max_ending_here=0;
}
if(max_so_far<max_ending_here){
max_so_far=max_ending_here;
}
}
System.out.println(max_so_far);
}
}
this program generates the max sum of sub array ..in this case its 19,using {5,9,-5,10}..
now i have to find the start and end index of this sub array ..how do i do that ??
This is a C program to solve this problem. I think logic is same for all languages so I posted this answer.
void findMaxSubArrayIndex(){
int n,*a;
int start=0,end=0,curr_max=0,prev_max=0,start_o=0,i;
scanf("%d",&n);
a = (int*)malloc(sizeof(int)*n);
for(i=0; i<n; i++) scanf("%d",a+i);
prev_max = a[0];
for(i=0; i<n; i++){
curr_max += a[i];
if(curr_max < 0){
start = i+1;
curr_max = 0;
}
else if(curr_max > prev_max){
end = i;
start_o = start;
prev_max = curr_max;
}
}
printf("%d %d \n",start_o,end);
}
Fixing Carl Saldanha solution:
int max_ending_here = 0;
int max_so_far = 0;
int _start = 0;
int start = 0;
int end = -1;
for(int i=0; i<array.length; i++) {
max_ending_here = max_ending_here + array[i];
if (max_ending_here < 0) {
max_ending_here = 0;
_start = i+1;
}
if (max_ending_here > max_so_far) {
max_so_far = max_ending_here;
start = _start;
end = i;
}
}
Here is algorithm for maxsubarray:
public class MaxSubArray {
public static void main(String[] args) {
int[] intArr={3, -1, -1, -1, -1, -1, 2, 0, 0, 0 };
//int[] intArr = {-1, 3, -5, 4, 6, -1, 2, -7, 13, -3};
//int[] intArr={-6,-2,-3,-4,-1,-5,-5};
findMaxSubArray(intArr);
}
public static void findMaxSubArray(int[] inputArray){
int maxStartIndex=0;
int maxEndIndex=0;
int maxSum = Integer.MIN_VALUE;
int cumulativeSum= 0;
int maxStartIndexUntilNow=0;
for (int currentIndex = 0; currentIndex < inputArray.length; currentIndex++) {
int eachArrayItem = inputArray[currentIndex];
cumulativeSum+=eachArrayItem;
if(cumulativeSum>maxSum){
maxSum = cumulativeSum;
maxStartIndex=maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (cumulativeSum<0){
maxStartIndexUntilNow=currentIndex+1;
cumulativeSum=0;
}
}
System.out.println("Max sum : "+maxSum);
System.out.println("Max start index : "+maxStartIndex);
System.out.println("Max end index : "+maxEndIndex);
}
}
Here is a solution in python - Kadane's algorithm extended to print the start/end indexes
def max_subarray(array):
max_so_far = max_ending_here = array[0]
start_index = 0
end_index = 0
for i in range(1, len(array) -1):
temp_start_index = temp_end_index = None
if array[i] > (max_ending_here + array[i]):
temp_start_index = temp_end_index = i
max_ending_here = array[i]
else:
temp_end_index = i
max_ending_here = max_ending_here + array[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
if temp_start_index != None:
start_index = temp_start_index
end_index = i
print max_so_far, start_index, end_index
if __name__ == "__main__":
array = [-2, 1, -3, 4, -1, 2, 1, 8, -5, 4]
max_subarray(array)
In python solving 3 problem i.e., sum, array elements and index.
def max_sum_subarray(arr):
current_sum = arr[0]
max_sum = arr[0]
curr_array = [arr[0]]
final_array=[]
s = 0
start = 0
e = 0
end = 0
for i in range(1,len(arr)):
element = arr[i]
if current_sum+element > element:
curr_array.append(element)
current_sum = current_sum+element
e += 1
else:
curr_array = [element]
current_sum = element
s = i
if current_sum > max_sum:
final_array = curr_array[:]
start = s
end = e
max_sum = current_sum
print("Original given array is : ", arr)
print("The array elements that are included in the sum are : ",final_array)
print("The starting and ending index are {} and {} respectively.".format(start, end))
print("The maximum sum is : ", max_sum)
# Driver code
arr = [-12, 15, -13, 14, -1, 2, 1, -5, 4]
max_sum_subarray(arr)
By Om Prasad Nayak
Like This
public static void main(String[] args) {
int arr[]= {0,-1,2,-3,5,9,-5,10};
int max_ending_here=0;
int max_so_far=0;
int start =0;
int end=0;
for(int i=0;i< arr.length;i++){
max_ending_here=max_ending_here+arr[i];
if(max_ending_here<0)
{
start=i+1; //Every time it goes negative start from next index
max_ending_here=0;
}
else
end =i; //As long as its positive keep updating the end
if(max_so_far<max_ending_here){
max_so_far=max_ending_here;
}
}
System.out.println(max_so_far);
}
Okay so there was a problem in the above solution as pointed to Steve P. This is another solution which should work for all
public static int[] compareSub(int arr[]){
int start=-1;
int end=-1;
int max=0;
if(arr.length>0){
//Get that many array elements and compare all of them.
//Then compare their max to the overall max
start=0;end=0;max=arr[0];
for(int arrSize=1;arrSize<arr.length;arrSize++){
for(int i=0;i<arr.length-arrSize+1;i++){
int potentialMax=sumOfSub(arr,i,i+arrSize);
if(potentialMax>max){
max=potentialMax;
start=i;
end=i+arrSize-1;
}
}
}
}
return new int[]{start,end,max};
}
public static int sumOfSub(int arr[],int start,int end){
int sum=0;
for(int i=start;i<end;i++)
sum+=arr[i];
return sum;
}
The question is somewhat unclear but I'm guessing a "sub-array" is half the arr object.
A lame way to do this like this
public int sum(int[] arr){
int total = 0;
for(int index : arr){
total += index;
}
return total;
}
public void foo(){
int arr[] = {0,-1,2,-3,5,9,-5,10};
int subArr1[] = new int[(arr.length/2)];
int subArr2[] = new int[(arr.length/2)];
for(int i = 0; i < arr.length/2; i++){
// Lazy hack, might want to double check this...
subArr1[i] = arr[i];
subArr2[i] = arr[((arr.length -1) -i)];
}
int sumArr1 = sum(subArr1);
int sumArr2 = sum(subArr2);
}
I image this might not work if the arr contains an odd number of elements.
If you want access to a higher level of support convert the primvate arrays to a List object
List<Integer> list = Arrays.asList(arr);
This way you have access to a collection object functionality.
Also if you have the time, take a look at the higher order functional called reduce. You will need a library that supports functional programming. Guava or lambdaJ might have a reduce method. I know that apache-commons lacks one, unless you want to hack to together it.
The only thing I have to add (to several solutions posted here) is to cover the case that all the integers are negative, in which case the max sub array will be just the max element. Pretty easy to do that.. just have to track max element and index of the index of the max element as you iterate through it. If the max element is negative, return it's index instead.
There is also the case of overflow to possibly handle. I've seen algorithm tests that take than into account.. IE, suppose MAXINT was one of the elements and you tried to add to it. I believe some of the Codility (coding interview screeners) tests take that into account.
public static void maxSubArray(int []arr){
int sum=0,j=0;
int temp[] = new int[arr.length];
for(int i=0;i<arr.length;i++,j++){
sum = sum + arr[i];
if(sum <= 0){
sum =0;
temp[j] = -1;
}else{
temp[j] = i;
}
}
rollback(temp,arr);
}
public static void rollback(int [] temp , int[] arr){
int s =0,start=0 ;
int maxTillNow = 0,count =0;
String str1 = "",str2="";
System.out.println("============");
// find the continuos index
for(int i=0;i<temp.length;i++){
if(temp[i] != -1){
s += arr[temp[i]];
if(s > maxTillNow){
if(count == 0){
str1 = "" + start;
}
count++;
maxTillNow = s;
str2 = " " + temp[i];
}
}else{
s=0;
count =0;
if(i != temp.length-1)
start = temp[i+1];
}
}
System.out.println("Max sum will be ==== >> " + maxTillNow);
System.out.print("start from ---> "+str1 + " end to --- >> " +str2);
}
public void MaxSubArray(int[] arr)
{
int MaxSoFar = 0;
int CurrentMax = 0;
int ActualStart=0,TempStart=0,End = 0;
for(int i =0 ; i<arr.Length;i++)
{
CurrentMax += arr[i];
if(CurrentMax<0)
{
CurrentMax = 0;
TempStart = i + 1;
}
if(MaxSoFar<CurrentMax)
{
MaxSoFar = CurrentMax;
ActualStart = TempStart;
End = i;
}
}
Console.WriteLine(ActualStart.ToString()+End.ToString());
}
An O(n) solution in C would be :-
void maxsumindex(int arr[], int len)
{
int maxsum = INT_MIN, cur_sum = 0, start=0, end=0, max = INT_MIN, maxp = -1, flag = 0;
for(int i=0;i<len;i++)
{
if(max < arr[i]){
max = arr[i];
maxp = i;
}
cur_sum += arr[i];
if(cur_sum < 0)
{
cur_sum = 0;
start = i+1;
}
else flag = 1;
if(maxsum < cur_sum)
{
maxsum = cur_sum;
end = i;
}
}
//This is the case when all elements are negative
if(flag == 0)
{
printf("Max sum subarray = {%d}\n",arr[maxp]);
return;
}
printf("Max sum subarray = {");
for(int i=start;i<=end;i++)
printf("%d ",arr[i]);
printf("}\n");
}
Here is a solution in Go using Kadane's Algorithm
func maxSubArr(A []int) (int, int, int) {
start, currStart, end, maxSum := 0, 0, 0, A[0]
maxAtI := A[0]
for i := 1; i < len(A); i++ {
if maxAtI > 0 {
maxAtI += A[i]
} else {
maxAtI = A[i]
currStart = i
}
if maxAtI > maxSum {
maxSum = maxAtI
start = currStart
end = i
}
}
return start, end, maxSum
}
Here is a C++ solution.
void maxSubArraySum(int *a, int size) {
int local_max = a[0];
int global_max = a[0];
int sum_so_far = a[0];
int start = 0, end = 0;
int tmp_start = 0;
for (int i = 1; i < size; i++) {
sum_so_far = a[i] + local_max;
if (sum_so_far > a[i]) {
local_max = sum_so_far;
} else {
tmp_start = i;
local_max = a[i];
}
if (global_max < local_max) {
global_max = local_max;
start = tmp_start;
end = i;
}
}
cout<<"Start Index: "<<start<<endl;
cout<<"End Index: "<<end<<endl;
cout<<"Maximum Sum: "<<global_max<<endl;
}
int main() {
int arr[] = {4, -3, -2, 2, 3, 1, -2, -3, 4,2, -6, -3, -1, 3, 1, 2};
maxSubArraySum(arr, sizeof(arr)/sizeof(arr[0]));
return 0;
}
pair<int,int> maxSumPair(vector<int> arr) {
int n = arr.size();`
int currSum = arr[0], maxSoFar = arr[0];
int start = 0, end ,prev = currSum;
unordered_map<int,pair<int,int>> mp;
for(int i = 1 ; i < n ; i++) {
prev = currSum;
if(currSum == arr[i]) {
end = i-1;
mp.insert({currSum,{start,end}});
start = i;
}
if(maxSoFar < currSum) {
maxSoFar = currSum;
end = i;
mp.insert({currSum,{start,end}});
}
}
int maxSum = INT_MIN;
for(auto it: mp) {
if(it.first > maxSum) {
maxSum = it.first;
}
}
return mp[maxSum];
}
int maxSubarraySum(int arr[], int n){
int max_so_far = -1 * Integer.MAX_VALUE;
int max_curr = 0;
int start = 0;
int end = 0;
for(int i=0; i < arr.length; i++){
max_curr = max_curr + arr[i];
if(max_so_far < max_curr){
max_so_far = max_curr;
}
if( max_curr < 0){
max_curr = 0;
start = i+1;
}
else
end = i;
}
start = end < start ? end : start;
System.out.println( start + "..." + end);
return max_so_far;
}
Maximum sub array in golang implementation
package main
import (
"fmt"
)
func main() {
in := []int{-2, -12, 23, -10, 11, -6, -1}
a, b := max(in)
fmt.Println(a)
fmt.Println(b)
}
func max(in []int) ([]int, int) {
var p, r, sum, sf, psf int
if len(in) == 0 {
return in, 0
}
sum = in[0]
for i, n := range in {
sf += n
if sf > sum {
sum = sf
p = psf
r = i
}
if sf <= 0 {
psf = i + 1
sf = 0
}
}
return in[p : r+1], sum
}
I think this will help to get the start and end index
// Time Complexity = O(N)
// Space Complexity = O(1)
public static int maxSum2(int[] nums){
int globalSum = Integer.MIN_VALUE;
int currentSum = 0;
int start=0;
int end=0;
for(int i=0; i<nums.length;i++){
currentSum += nums[i];
if (currentSum>globalSum){
globalSum = currentSum;
end = i;
}
if (currentSum<0){
currentSum=0;
start = i+1;
}
}
System.out.println(start + " " + end);
return globalSum;
}

How to find second largest number in an array in Java?

I'm just practicing some MIT java assignments. But, I'm not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13
public class Marathon {
public static void main(String[] arguments) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
"Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265 };
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + times[i]);
}
System.out.println();
System.out.println("Largest Timing " + Largest(times));
System.out.println();
}
public static int Largest(int[] times) {
int maxValue = times[0];
for (int i = 1; i < times.length; i++) {
if (times[i] > maxValue) {
maxValue = times[i];
}
}
return maxValue;
}
}
Instead of resorting to sorting the array, you can simply do the following:
Keep a largestValue and a secondLargestValue
Loop through the entire array once, for each element:
Check to see if the current element is greater than largestValue:
If so, assign largestValue to secondLargestValue, then assign the current element to largestValue (think of it as shifting everything down by 1)
If not, check to see if the current element is greater than secondLargestValue
If so, assign the current element to secondLargestValue
If not, do nothing.
O(n) run time
O(1) space requirement
Sorting the array simply to find an order statistics is too wasteful. You can find the second largest element by following an algorithm that resembles the one that you already have, with an additional variable representing the second largest number.
Currently, the next element could be larger than the max or equal to/smaller than the max, hence a single if is sufficient:
if (times[i] > maxValue) {
maxValue = times[i];
}
With two variables to consider, the next element could be
Greater than the max - the max becomes second largest, and the next element becomes the max
Smaller than the max but greater than the second largest - the next element becomes second largest.
A special care must be taken about the initial state. Look at the first two items, and assign the larger one to the max and the smaller to the second largest; start looping at the element number three, if there is one.
Here is how you can code it:
if (times[i] > maxValue) {
secondLargest = maxValue;
maxValue = times[i];
} else if (times[i] > secondLargest) {
secondLargest = times[i];
}
Generally speaking:
Have two values -- "largest" and "notQuite".
Initialize both to -9999 or whatever.
Scan through your list. If the number is larger than "largest", set "largest" to that number. But before you do that, copy the old "largest" value to "notQuite".
If, on the other hand, the number is smaller than "largest" but is larger than "notQuite", set "notQuite" to that number.
When you're done examining all the numbers, "notQuite" contains the second-largest.
And note that, as you fill in the above numbers, you can also keep a "largestIndex" and "notQuiteIndex" and fill those in with the corresponding array index values, so you can identify the "winning" value. Unfortunately, though, if there are multiple identical "largest" or "secondLargest" values the simple index scheme doesn't work and you need to keep a list of some sort.
private static int secLargest(int[] numbers) {
int maxVal = 0;
int nextMaxVal = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
if (numbers[i] < maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
}
return nextMaxVal;
}
private void secondLargest(int arr[]){
int maxOne=arr[0];
int maxTwo=arr[1];
for(int i=0;i<arr.length;i++){
if(arr[i]>maxOne){
maxTwo=maxOne;
maxOne=arr[i];
}else if (arr[i]>maxTwo) {
maxTwo=arr[i];
}
}
System.out.println(maxOne);
System.out.println(maxTwo);
}
int largest=time[0];
int secondLargest=largest;
for(int i=0;i<time.length;i++){
if(time[i]>largest){
secondLargest=largest;
largest=time[i];
}
else if(secondLargest<time[i] && time[i]<largest || secondLargest>=largest)
secondLargest=time[i];
}
return secondLargest;
public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrieved in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.
It will also extract second largest number if largest number occours two times as well as in a single for loop.
import java.util.*;
public class SecondLargestInArray
{
public static void main(String[] args)
{
int arr[] = {99,14,46,47,86,92,52,48,36,66,85,92};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
secondLargest = largest;
largest = arr[i];
}
else if((arr[i]<largest && arr[i]>secondLargest) || largest==secondLargest)
{
secondLargest=arr[i];
}
}
System.out.println("\nLargest number is:" + largest);
System.out.println("\nSecond largest number is:" + secondLargest);
}
}
Find the second largest element in the given array:
public static void findSecondMax(){
int[] arr = {3, 2, 20, 4, 1, 9, 6, 3, 8};
int max = 0;
int secondMax = 0;
for(int i =0; i< arr.length; i++) {
if(max < arr[i]) max = arr[i];
if((max > arr[i]) && (secondMax < arr[i])) secondMax = arr[i];
}
System.out.println(secondMax);
}
public static void main (String args[]) {
int [] arr = {1,4,3,10,4,8,20,5,33};
int largest = 0;
int secondLargest = 0;
for (int x : arr) {
if (x > largest) {
secondLargest = largest;
largest = x;
}
else if (x > secondLargest) {
secondLargest = x;
}
}
System.out.println("secondLargest:"+secondLargest);
}
Updated : Changed to Java.
class Main {
public static void main(String[] args) {
int a = Integer.MIN_VALUE;
int b = Integer.MIN_VALUE;
int[] arr = {44,6,43,8,9,-10,4,15,3,-30,23};
for(int i=0; i < arr.length; i++){
if( arr[i] > a || arr[i] > b ){
if( a < b ) {
a = arr[i];
} else {
b = arr[i];
}
}
}
int secondLargest = a < b ? a : b;
System.out.println(secondLargest);
}
}

Programming Test - Codility - Dominator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I just had a codility problem give me a hard time and I'm still trying to figure out how the space and time complexity constraints could have been met.
The problem is as follows:
A dominant member in the array is one that occupies over half the positions in the array, for example:
{3, 67, 23, 67, 67}
67 is a dominant member because it appears in the array in 3/5 (>50%) positions.
Now, you are expected to provide a method that takes in an array and returns an index of the dominant member if one exists and -1 if there is none.
Easy, right? Well, I could have solved the problem handily if it were not for the following constraints:
Expected time complexity is O(n)
Expected space complexity is O(1)
I can see how you could solve this for O(n) time with O(n) space complexities as well as O(n^2) time with O(1) space complexities, but not one that meets both O(n) time and O(1) space.
I would really appreciate seeing a solution to this problem. Don't worry, the deadline has passed a few hours ago (I only had 30 minutes), so I'm not trying to cheat. Thanks.
Googled "computing dominant member of array", it was the first result. See the algorithm described on page 3.
element x;
int count ← 0;
For(i = 0 to n − 1) {
if(count == 0) { x ← A[i]; count++; }
else if (A[i] == x) count++;
else count−−;
}
Check if x is dominant element by scanning array A
Basically observe that if you find two different elements in the array, you can remove them both without changing the dominant element on the remainder. This code just keeps tossing out pairs of different elements, keeping track of the number of times it has seen the single remaining unpaired element.
Find the median with BFPRT, aka median of medians (O(N) time, O(1) space). Then scan through the array -- if one number dominates, the median will be equal to that number. Walk through the array and count the number of instances of that number. If it's over half the array, it's the dominator. Otherwise, there is no dominator.
Adding a Java 100/100 O(N) time with O(1) space:
https://codility.com/demo/results/demoPNG8BT-KEH/
class Solution {
public int solution(int[] A) {
int indexOfCandidate = -1;
int stackCounter = 0, candidate=-1, value=-1, i =0;
for(int element: A ) {
if (stackCounter == 0) {
value = element;
++stackCounter;
indexOfCandidate = i;
} else {
if (value == element) {
++stackCounter;
} else {
--stackCounter;
}
}
++i;
}
if (stackCounter > 0 ) {
candidate = value;
} else {
return -1;
}
int countRepetitions = 0;
for (int element: A) {
if( element == candidate) {
++countRepetitions;
}
if(countRepetitions > (A.length / 2)) {
return indexOfCandidate;
}
}
return -1;
}
}
If you want to see the Java source code it's here, I added some test cases as comments as the beginning of the file.
Java solution with score 100%
public int solution(int[] array) {
int candidate=0;
int counter = 0;
// Find candidate for leader
for(int i=0; i<array.length; i++){
if(counter == 0) candidate = i;
if(array[i] == array[candidate]){
counter++;
}else {
counter--;
}
}
// Count candidate occurrences in array
counter = 0;
for(int i=0; i<array.length; i++){
if(array[i] == array[candidate]) counter++;
}
// Check that candidate occurs more than array.lenght/2
return counter>array.length/2 ? candidate : -1;
}
In python, we are lucky some smart people have bothered to implement efficient helpers using C and shipped it in the standard library. The collections.Counter is useful here.
>>> data = [3, 67, 23, 67, 67]
>>> from collections import Counter
>>> counter = Counter(data) # counter accepts any sequence/iterable
>>> counter # dict like object, where values are the occurrence
Counter({67: 3, 3: 1, 23: 1})
>>> common = counter.most_common()[0]
>>> common
(67, 3)
>>> common[0] if common[1] > len(data) / 2.0 + 1 else -1
67
>>>
If you prefer a function here is one ...
>>> def dominator(seq):
counter = Counter(seq)
common = counter.most_common()[0]
return common[0] if common[1] > len(seq) / 2.0 + 1 else -1
...
>>> dominator([1, 3, 6, 7, 6, 8, 6])
-1
>>> dominator([1, 3, 6, 7, 6, 8, 6, 6])
6
This question looks hard if a small trick does not come to the mind :). I found this trick in this document of codility : https://codility.com/media/train/6-Leader.pdf.
The linear solution is explained at the bottom of this document.
I implemented the following java program which gave me a score of 100 on the same lines.
public int solution(int[] A) {
Stack<Integer> stack = new Stack<Integer>();
for (int i =0; i < A.length; i++)
{
if (stack.empty())
stack.push(new Integer(A[i]));
else
{
int topElem = stack.peek().intValue();
if (topElem == A[i])
{
stack.push(new Integer(A[i]));
}
else
{
stack.pop();
}
}
}
if (stack.empty())
return -1;
int elem = stack.peek().intValue();
int count = 0;
int index = 0;
for (int i = 0; i < A.length; i++)
{
if (elem == A[i])
{
count++;
index = i;
}
}
if (count > ((double)A.length/2.0))
return index;
else
return -1;
}
Here's my C solution which scores 100%
int solution(int A[], int N) {
int candidate;
int count = 0;
int i;
// 1. Find most likely candidate for the leader
for(i = 0; i < N; i++){
// change candidate when count reaches 0
if(count == 0) candidate = i;
// count occurrences of candidate
if(A[i] == A[candidate]) count++;
else count--;
}
// 2. Verify that candidate occurs more than N/2 times
count = 0;
for(i = 0; i < N; i++) if(A[i] == A[candidate]) count++;
if (count <= N/2) return -1;
return candidate; // return index of leader
}
100%
import java.util.HashMap;
import java.util.Map;
class Solution {
public static int solution(int[] A) {
final int N = A.length;
Map<Integer, Integer> mapOfOccur = new HashMap((N/2)+1);
for(int i=0; i<N; i++){
Integer count = mapOfOccur.get(A[i]);
if(count == null){
count = 1;
mapOfOccur.put(A[i],count);
}else{
mapOfOccur.replace(A[i], count, ++count);
}
if(count > N/2)
return i;
}
return -1;
}
}
Does it have to be a particularly good algorithm? ;-)
static int dominant(final int... set) {
final int[] freqs = new int[Integer.MAX_VALUE];
for (int n : set) {
++freqs[n];
}
int dom_freq = Integer.MIN_VALUE;
int dom_idx = -1;
int dom_n = -1;
for (int i = set.length - 1; i >= 0; --i) {
final int n = set[i];
if (dom_n != n) {
final int freq = freqs[n];
if (freq > dom_freq) {
dom_freq = freq;
dom_n = n;
dom_idx = i;
} else if (freq == dom_freq) {
dom_idx = -1;
}
}
}
return dom_idx;
}
(this was primarily meant to poke fun at the requirements)
Consider this 100/100 solution in Ruby:
# Algorithm, as described in https://codility.com/media/train/6-Leader.pdf:
#
# * Iterate once to find a candidate for dominator.
# * Count number of candidate occurences for the final conclusion.
def solution(ar)
n_occu = 0
candidate = index = nil
ar.each_with_index do |elem, i|
if n_occu < 1
# Here comes a new dominator candidate.
candidate = elem
index = i
n_occu += 1
else
if candidate == elem
n_occu += 1
else
n_occu -= 1
end
end # if n_occu < 1
end
# Method result. -1 if no dominator.
# Count number of occurences to check if candidate is really a dominator.
if n_occu > 0 and ar.count {|_| _ == candidate} > ar.size/2
index
else
-1
end
end
#--------------------------------------- Tests
def test
sets = []
sets << ["4666688", [1, 2, 3, 4], [4, 6, 6, 6, 6, 8, 8]]
sets << ["333311", [0, 1, 2, 3], [3, 3, 3, 3, 1, 1]]
sets << ["313131", [-1], [3, 1, 3, 1, 3, 1]]
sets << ["113333", [2, 3, 4, 5], [1, 1, 3, 3, 3, 3]]
sets.each do |name, one_of_expected, ar|
out = solution(ar)
raise "FAILURE at test #{name.inspect}: #{out.inspect} not in #{expected.inspect}" if not one_of_expected.include? out
end
puts "SUCCESS: All tests passed"
end
Here is an easy to read, 100% score version in Objective-c
if (A.count > 100000)
return -1;
NSInteger occur = 0;
NSNumber *candidate = nil;
for (NSNumber *element in A){
if (!candidate){
candidate = element;
occur = 1;
continue;
}
if ([candidate isEqualToNumber:element]){
occur++;
}else{
if (occur == 1){
candidate = element;
continue;
}else{
occur--;
}
}
}
if (candidate){
occur = 0;
for (NSNumber *element in A){
if ([candidate isEqualToNumber:element])
occur++;
}
if (occur > A.count / 2)
return [A indexOfObject:candidate];
}
return -1;
100% score JavaScript solution. Technically it's O(nlogn) but still passed.
function solution(A) {
if (A.length == 0)
return -1;
var S = A.slice(0).sort(function(a, b) {
return a - b;
});
var domThresh = A.length/2;
var c = S[Math.floor(domThresh)];
var domCount = 0;
for (var i = 0; i < A.length; i++) {
if (A[i] == c)
domCount++;
if (domCount > domThresh)
return i;
}
return -1;
}
This is the solution in VB.NET with 100% performance.
Dim result As Integer = 0
Dim i, ladderVal, LadderCount, size, valCount As Integer
ladderVal = 0
LadderCount = 0
size = A.Length
If size > 0 Then
For i = 1 To size - 1
If LadderCount = 0 Then
LadderCount += 1
ladderVal = A(i)
Else
If A(i) = ladderVal Then
LadderCount += 1
Else
LadderCount -= 1
End If
End If
Next
valCount = 0
For i = 0 To size - 1
If A(i) = ladderVal Then
valCount += 1
End If
Next
If valCount <= size / 2 Then
result = 0
Else
LadderCount = 0
For i = 0 To size - 1
If A(i) = ladderVal Then
valCount -= 1
LadderCount += 1
End If
If LadderCount > (LadderCount + 1) / 2 And (valCount > (size - (i + 1)) / 2) Then
result += 1
End If
Next
End If
End If
Return result
See the correctness and performance of the code
Below solution resolves in complexity O(N).
public int solution(int A[]){
int dominatorValue=-1;
if(A != null && A.length>0){
Hashtable<Integer, Integer> count=new Hashtable<>();
dominatorValue=A[0];
int big=0;
for (int i = 0; i < A.length; i++) {
int value=0;
try{
value=count.get(A[i]);
value++;
}catch(Exception e){
}
count.put(A[i], value);
if(value>big){
big=value;
dominatorValue=A[i];
}
}
}
return dominatorValue;
}
100% in PHP https://codility.com/demo/results/trainingVRQGQ9-NJP/
function solution($A){
if (empty($A)) return -1;
$copy = array_count_values($A); // 3 => 7, value => number of repetition
$max_repetition = max($copy); // at least 1 because the array is not empty
$dominator = array_search($max_repetition, $copy);
if ($max_repetition > count($A) / 2) return array_search($dominator, $A); else return -1;
}
i test my code its work fine in arrays lengths between 2 to 9
public static int sol (int []a)
{
int count = 0 ;
int candidateIndex = -1;
for (int i = 0; i <a.length ; i++)
{
int nextIndex = 0;
int nextOfNextIndex = 0;
if(i<a.length-2)
{
nextIndex = i+1;
nextOfNextIndex = i+2;
}
if(count==0)
{
candidateIndex = i;
}
if(a[candidateIndex]== a[nextIndex])
{
count++;
}
if (a[candidateIndex]==a[nextOfNextIndex])
{
count++;
}
}
count -- ;
return count>a.length/2?candidateIndex:-1;
}
Adding a Java 100/100 O(N) time with O(1) space:
// you can also use imports, for example:
import java.util.Stack;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int count = 0;
Stack<Integer> integerStack = new Stack<Integer>();
for (int i = 0; i < A.length; i++) {
if (integerStack.isEmpty()) {
integerStack.push(A[i]);
} else if (integerStack.size() > 0) {
if (integerStack.peek() == A[i])
integerStack.push(A[i]);
else
integerStack.pop();
}
}
if (!integerStack.isEmpty()) {
for (int i = 0; i < integerStack.size(); i++) {
for (int j = 0; j < A.length; j++) {
if (integerStack.get(i) == A[j])
count++;
if (count > A.length / 2)
return j;
}
count = 0;
}
}
return -1;
}
}
Here is test result from codility.
I think this question has already been resolved somewhere. The "official" solution should be :
public int dominator(int[] A) {
int N = A.length;
for(int i = 0; i< N/2+1; i++)
{
int count=1;
for(int j = i+1; j < N; j++)
{
if (A[i]==A[j]) {count++; if (count > (N/2)) return i;}
}
}
return -1;
}
How about sorting the array first? You then compare middle and first and last elements of the sorted array to find the dominant element.
public Integer findDominator(int[] arr) {
int[] arrCopy = arr.clone();
Arrays.sort(arrCopy);
int length = arrCopy.length;
int middleIndx = (length - 1) /2;
int middleIdxRight;
int middleIdxLeft = middleIndx;
if (length % 2 == 0) {
middleIdxRight = middleIndx+1;
} else {
middleIdxRight = middleIndx;
}
if (arrCopy[0] == arrCopy[middleIdxRight]) {
return arrCopy[0];
}
if (arrCopy[middleIdxLeft] == arrCopy[length -1]) {
return arrCopy[middleIdxLeft];
}
return null;
}
C#
int dominant = 0;
int repeat = 0;
int? repeatedNr = null;
int maxLenght = A.Length;
int halfLenght = A.Length / 2;
int[] repeations = new int[A.Length];
for (int i = 0; i < A.Length; i++)
{
repeatedNr = A[i];
for (int j = 0; j < A.Length; j++)
{
if (repeatedNr == A[j])
{
repeations[i]++;
}
}
}
repeatedNr = null;
for (int i = 0; i < repeations.Length; i++)
{
if (repeations[i] > repeat)
{
repeat = repeations[i];
repeatedNr = A[i];
}
}
if (repeat > halfLenght)
dominant = int.Parse(repeatedNr.ToString());
class Program
{
static void Main(string[] args)
{
int []A= new int[] {3,6,2,6};
int[] B = new int[A.Length];
Program obj = new Program();
obj.ABC(A,B);
}
public int ABC(int []A, int []B)
{
int i,j;
int n= A.Length;
for (j=0; j<n ;j++)
{
int count = 1;
for (i = 0; i < n; i++)
{
if ((A[j]== A[i] && i!=j))
{
count++;
}
}
int finalCount = count;
B[j] = finalCount;// to store the no of times a number is repeated
}
// int finalCount = count / 2;
int finalCount1 = B.Max();// see which number occurred max times
if (finalCount1 > (n / 2))
{ Console.WriteLine(finalCount1); Console.ReadLine(); }
else
{ Console.WriteLine("no number found"); Console.ReadLine(); }
return -1;
}
}
In Ruby you can do something like
def dominant(a)
hash = {}
0.upto(a.length) do |index|
element = a[index]
hash[element] = (hash[element] ? hash[element] + 1 : 1)
end
res = hash.find{|k,v| v > a.length / 2}.first rescue nil
res ||= -1
return res
end
#Keith Randall solution is not working for {1,1,2,2,3,2,2}
his solution was:
element x;
int count ← 0;
For(i = 0 to n − 1) {
if(count == 0) { x ← A[i]; count++; }
else if (A[i] == x) count++;
else count−−;
}
Check if x is dominant element by scanning array A
I converted it into java as below:
int x = 0;
int count = 0;
for(int i = 0; i < (arr.length - 1); i++) {
if(count == 0) {
x = arr[i];
count++;
}
else if (arr[i] == x)
count++;
else count--;
}
return x;
Out put : 3
Expected: 2
This is my answer in Java: I store a count in seperate array which counts duplicates of each of the entries of the input array and then keeps a pointer to the array position that has the most duplicates. This is the dominator.
private static void dom(int[] a) {
int position = 0;
int max = 0;
int score = 0;
int counter = 0;
int[]result = new int[a.length];
for(int i = 0; i < a.length; i++){
score = 0;
for(int c = 0; c < a.length;c++){
if(a[i] == a[c] && c != i ){
score = score + 1;
result[i] = score;
if(result[i] > position){
position = i;
}
}
}
}
//This is just to facilitate the print function and MAX = the number of times that dominator number was found in the list.
for(int x = 0 ; x < result.length-1; x++){
if(result[x] > max){
max = result[x] + 1;
}
}
System.out.println(" The following number is the dominator " + a[position] + " it appears a total of " + max);
}

Categories