Searching a value using for-loop and - java

The question is this:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Input: [4,1,2,1,2]
Output: 4
my code is:
public static int singleNumber(int[] nums) {
int answer = 0;
for (int i =0; i<nums.length-1; i++) {
for(int j = i+1; j<nums.length; j++) {
if(nums[i] != nums[j]) {
answer = nums[i]; //this should be where I am wrong.
}
}
}
return answer;
}
I know that the output was 4 and then now it will be changed to 1.
I'm trying to figure out how not to change the found value once found.

The logic is wrong - your inner loop finds every number that isn't the only number in the array.
I'd maintain a Set to track the numbers I've encountered. The first time you encounter a number, you add it to the Set. The second time you encounter it, you remove it from the Set. Once you're done going over the array, you'd have a Set with a single element, which is your answer:
public static int singleNumber(int[] nums) {
Set<Integer> unique = new HashSet<>();
for (int num : nums) {
// add returns true if num is indeed new to unique
if (!unique.add(num)) {
unique.remove(num);
}
}
return unique.iterator().next();
}

For this problem, i would to bitwise XOR of the numbers. The numbers that are equal will cancel one another and only single integer will be the final value.
public static int singleNumber(int[] nums) {
int answer = 0;
for (int i =0; i<nums.length; i++) {
answer = answer ^ nums[i];
}
return answer;
}

below changes to your method will give you the expected answer
public static int singleNumber(int[] nums) {
int temp = 0;
int answer = 0;
for (int i = 0; i < nums.length; i++) {
boolean flag = true;
temp = nums[i];
for (int j = 0; j < nums.length; j++) {
if (temp == nums[j]) {
if (i != j) {// if a match found then the loop will terminate
flag = false;
break;
}
}
}
if (flag == true) {
answer = temp;
}
}
return answer;
}

Here is another solution using Collectors.groupingBy from Java 8 :
public static int singleNumber(int[] nums) {
return Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(a -> a, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() == 1).findFirst().get().getKey();
}
the idea is :
group by number of occurence
then find the one which is repeated just one time
Note I assume that your array contain at least one element, else you can check the length before you search then throw an exception like this :
public static int singleNumber(int[] nums) throws IllegalArgumentException{
if(nums.length == 0){
throw new IllegalArgumentException("empty array");
}
return Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(a -> a, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() == 1).findFirst().get().getKey();
}
More deeper, If you want to avoid the situation where there are multiple number repeated just one time you can use :
public static int singleNumber(int[] nums) throws IllegalArgumentException {
if (nums.length == 0) {
throw new IllegalArgumentException("empty array");
}
Map<Integer, Long> grouping = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(a -> a, Collectors.counting()));
if (grouping.values().stream().filter(c -> c == 1).count() > 1) {
throw new IllegalArgumentException("more than one element is repeated one time");
}
return grouping.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst().get().getKey();
}

Here is a solution which uses ArrayList.indexOf and ArrayList.lastIndexOf. If they are same, you have your answer.
public static int singleNumber(int[] nums) {
int answer = 0;
//ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(nums));
ArrayList al = new ArrayList();
for (int i =0; i < nums.length; i++) {
al.add(nums[i]);
}
for (int i =0; i < nums.length; i++) {
int test = nums[i];
if(al.indexOf(test) == al.lastIndexOf(test)){
answer = nums[i];
}
}
return answer;
}

Try this:
int[] nums = new int[] {4,2,1,2,1};
int answer = 0;
for (int i =0; i<nums.length-1; i++) {
int times = 0;
int target = nums[i];
for(int j : nums) {
if(j == target) {
times++;
if(times == 2) {
break;
}
}
}
if(times == 1) {
answer = target;
break;
}
}
System.out.println(answer);
you have to go into every number and count how meny are in the array if there is only 1 you instantly stop the loop end set the answer

Related

Given an array of integer , return the number of 9's in the array

Basically the aim of this problem is to count the number of times the number 9 is typed in the array, for example, arrayCountNines([1, 9, 9, 3, 9]) = 3
I have tried doing a Stream of the numbers, for example by using .collect but that didn't seem to work. Also tried HashMaps
public class NewClass4 {
public int arrayCountNines(int[] nums) {
HashMap < Character, Integer > map = new HashMap<>();
for (int i =0; i<nums.length; i++) {
char[] charr = String.valueOf(nums[i]).toCharArray();
for(int j = 0; j<charr.length; j++) {
if(map.containsKey(charr[j])) {
map.put(charr[j], map.get(charr[j])+1);
}
else {
map.put(charr[j], 1);
}
}
}
return 1;
}
}
]1
It doesn't return the number of times 9 is in the array
public int arrayCountNines(int[] nums) {
return (int) Arrays.stream(nums).filter(value -> value == 9).count();
}
Try this simple approach:
public int arrayCountNines(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 9){
result++;
}
}
return result;
}
Can't you just iterate through the array using a for-loop and then add to a counter whenever the item is equal to 9?
...
int nineCounter = 0;
for(int i=0; i<array.length ; i++){
if(array[i] == 9){
nineCounter++;
}
}
return nineCounter;
Try that:
public int arrayCountNines(int[] nums) {
int count=0;
for (int i =0; i<nums.length; i++) {
int v = nums[i];
if (v==9) {
count++;
}
}
return count;
}

HackerRank Mininum Difference RunTimeError

My code throws a run-time error, can anyone explain why? My solution envolves adding to an array the differences between j and i, and then find the minimum of the two, only to return it. But for some reason it gives me a timeout error. The question is question is this:
We define the distance between two array values as the number of indices between the two values. Given A find the minimum distance between any pair of equal elements in the array. If no such value exists, print -1 The minimum difference is calculated by the difference between index j and index i
static int minimumDistances(int[] a) {
int[] difference = new int[a.length];
int lowest = 0;
boolean pairFound = false;
for(int i = 0; i < a.length; i++) {
for(int j = i + 1; j < a.length; j++) {
for(int l = 0; l < difference.length; l++) {
if(a[i] == a[j]) {
difference[l] = j - i;
pairFound = true;
} else if(pairFound == false) {
lowest = -1;
}
}
}
}
if(pairFound == true) {
lowest = difference[0];
for(int i = 0; i < difference.length; i++) {
if(difference[i] < lowest) {
lowest = difference[i];
}
}
}
return lowest;
}
Give this a try and check to see if this works:
int[] difference = new int[a.length];
You are looping 3 times, that is 𝓞(n³) too slow. Try a different approach.
Here is my code using streams.
static int minimumDistances(int[] a) {
Map<Integer,List<Integer>> map = IntStream.range(0, a.length).boxed()
.collect(Collectors.groupingBy(i -> a[i]));
return map.entrySet().stream().filter(m -> m.getValue().size() > 1)
.map(m -> m.getValue().stream()
.reduce((acc,val)-> Math.abs(acc - val)).get())
.mapToInt(Integer::valueOf).min().orElse(-1);
}

Output of Removing 3s does not come as expected

Given an array on numbers as input, remove all elements from the array which are either multiple of 3 or have the digit 3 in them. For e.g. 13 and 15 will be both removed from the array if they are present.
MyApproach
To remove 3, I have made function removeMultiple which first remove Multiple of 3 if it exist.And then I also made function removeDigit Which removes the digit 3 int it if the number is not multiple of 3.
But I am not getting expected output.
MyQuestion:What I am doing wrong in my code.Can anyone guide me?
#Edit:
boolean containsDigit3(int[] arr,int index)
{
boolean b1=false;
while(arr[index]>0)
{
int p=arr[index]%10;
if(p==3)
{
b1=true;
}
arr[index]=arr[index]/10;
}
if(b1==true)
return true;
else
return false;
}
boolean isMultipleOf3(int[] arr,int index)
{
boolean b1=false;
int p=arr[index]%3;
if(p==0)
{
b1=true;
}
if(b1==true)
return true;
else
return false;
}
public int[] remove(int[] arr)
{
// Array of max length
int p[] = new int[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++)
{
if (!isMultipleOf3(arr,i) && !containsDigit3(arr,i))
{
p[i] = arr[i];
++count;
}
}
// Array of right length - System.arraycopy not allowed?!
int[] q = new int[count];
for (int i = 0; i < q.length; ++i)
{
q[i] = p[i];
}
return q;
}
Parameters Actual Output Expected Output
'{24,27,30,31,34,37,40,42}' {0} {40}
Operating on full arrays might be more difficult than it has to be. Break down your code into small and accurate parts, don't mix up iterating and copying an array with checking-for-3-logic.
Consider this method to remove those unwanted elements:
public int[] remove(int[] arr) {
// Array of max length
int p[] = new int[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (!isMultipleOf3(arr[i]) && !containsDigit3(arr[i])) {
p[count] = arr[i];
++count;
}
}
// Array of right length - System.arraycopy not allowed?!
int[] q = new int[count];
for (int i = 0; i < q.length; ++i) {
q[i] = p[i];
}
return q;
}
Now you can focus on very, very simple methods for boolean isMultipleOf3(int i) and boolean containsDigit3(int i)
Here's some very basic implementations:
private boolean containsDigit3(int i) {
//indexOf returns position of character '3' in String that
//represents the number i. If '3' is not found it returns -1
//so indexOf('3') >= 0 is another way of saying "contains digit 3"
return Integer.toString(i).indexOf('3') >= 0;
}
private boolean isMultipleOf3(int i) {
return i%3 == 0;
}
I would write it like this
public int[] remove(int[] arr) {
return IntStream.of(arr)
.filter(i -> i % 3 != 0)
.filter(i -> !(""+i).contains("3"))
.toArray();
}
I have to hard code it.No inbuilt functions allowed.
In that case I would do something like the above except "hard coded"
public static int[] remove(int[] arr) {
int[] ret = new int[arr.length];
int count = 0;
OUTER:
for (int i : arr) {
if (i % 3 == 0)
continue;
int j = i;
while (j > 0) {
if (j % 10 == 3)
continue OUTER;
j /= 10;
}
ret[count++] = i;
}
// do the same as Arrays.copyOf(ret, count)
if (ret.length > count) {
int[] ret2 = new int[count];
for (int i = 0; i < count; i++)
ret2[i] = ret[i];
return ret2;
}
return ret;
}
so
int[] arr = {24, 27, 30, 31, 34, 37, 40, 42};
int[] arr2 = remove(arr);
System.out.println(Arrays.toString(arr2));
prints
[40]

Finding closest number to 0

I have an array of integers, and I need to find the one that's closest to zero (positive integers take priority over negative ones.)
Here is the code I have so far:
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
near = data[i];
}
}
System.out.println( near );
}
}
Currently I'm getting a result of -2 but I should be getting 2. What am I doing wrong?
This will do it in O(n) time:
int[] arr = {1,4,5,6,7,-1};
int closestIndex = 0;
int diff = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; ++i) {
int abs = Math.abs(arr[i]);
if (abs < diff) {
closestIndex = i;
diff = abs;
} else if (abs == diff && arr[i] > 0 && arr[closestIndex] < 0) {
//same distance to zero but positive
closestIndex =i;
}
}
System.out.println(arr[closestIndex ]);
If you are using java8:
import static java.lang.Math.abs;
import static java.lang.Math.max;
public class CloseToZero {
public static void main(String[] args) {
int[] str = {2,3,-2};
Arrays.stream(str).filter(i -> i != 0)
.reduce((a, b) -> abs(a) < abs(b) ? a : (abs(a) == abs(b) ? max(a, b) : b))
.ifPresent(System.out::println);
}
}
Sort the array (add one line of code) so the last number you pick up will be positive if the same absolute value is selected for a positive and negative numbers with the same distance.
Source code:
import java.util.Arrays;
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
Arrays.sort(data); // add this
System.out.println(Arrays.toString(data));
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
System.out.println("dist from " + data[i] + " = " + Math.abs(0 -data[i]));
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
near = data[i];
}
}
System.out.println( near );
}
}
Just add zero to this list.
Then sort the list
Arrays.sort(data);
then grab the number before or after the zero and pick the minimum one greater than zero
Assumption is that the array data has at least 1 value.
int closestToZero = 0;
for ( int i = 1; i < data.length; i++ )
{
if ( Math.abs(data[i]) < Math.abs(data[closestToZero]) ) closestToZero = i;
}
The value in closestToZero is the index of the value closest to zero, not the value itself.
static int Solve(int N, int[] A){
int min = A[0];
for (int i=1; i<N ; i++){
min = min > Math.abs(0- A[i]) ? Math.abs(0- A[i]) : Math.abs(min);
}
return min;
}
As you multiply data[i] with data[i], a value negative and a value positive will have the same impact.
For example, in your example: 2 and -2 will be 4. So, your code is not able to sort as you need.
So, here, it takes -2 as the near value since it has the same "weight" as 2.
I have same answer with different method,Using Collections and abs , we can solved.
static int Solve(int N, int[] A){
List<Integer> mInt=new ArrayList<>();
for ( int i=0; i < A.length; i++ ){
mInt.add(Math.abs(0 -A[i]));
}
return Collections.min(mInt);
}
That all,As simple as that
This is a very easy to read O(n) solution for this problem.
int bigestNegative = Integer.MIN_VALUE;
int smalestpositive = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < n; i++) {
//if the zero should be considered as result as well
if ( temperatures[i] == 0 ) {
result = 0;
break;
}
if ( temperatures[i] > 0 && temperatures[i] < smalestpositive ) {
smalestpositive = temperatures[i];
}
if ( temperatures[i] < 0 && temperatures[i] > bigestNegative ) {
bigestNegative = temperatures[i];
}
}
if( (Math.abs(bigestNegative)) < (Math.abs(smalestpositive)) && bigestNegative != Integer.MIN_VALUE)
result = bigestNegative;
else
result = smalestpositive;
System.out.println( result );
First convert the int array into stream. Then sort it with default sorting order. Then filter greater than zero & peek the first element & print it.
Do it in declarative style which describes 'what to do', not 'how to do'. This style is more readable.
int[] data = {2,3,-2};
IntStream.of(data)
.filter(i -> i>0)
.sorted()
.limit(1)
.forEach(System.out::println);
using Set Collection and abs methode to avoid complex algo
public static void main(String[] args) {
int [] temperature={0};
***// will erase double values and order them from small to big***
Set<Integer> s= new HashSet<Integer>();
if (temperature.length!=0) {
for(int i=0; i<temperature.length; i++) {
***// push the abs value to the set***
s.add(Math.abs(temperature[i]));
}
// remove a zero if exists in the set
while(s.contains(0)) {
s.remove(0);
}
***// get first (smallest) element of the set : by default it is sorted***
if (s.size()!=0) {
Iterator iter = s.iterator();
System.out.println(iter.next());
}
else System.out.println(0);
}
else System.out.println(0);
}
static int nearToZero(int[] A){
Arrays.sort(A);
int ans = 0;
List<Integer> list = Arrays.stream(A).boxed().collect(Collectors.toList());
List<Integer> toRemove = new ArrayList<>();
List<Integer> newList = new ArrayList<>();
for(int num: list){
if(newList.contains(num)) toRemove.add(num);
else newList.add(num);
}
list.removeAll(toRemove);
for(int num : list){
if(num == 0 ) return 0;
if(ans == 0 )ans = num;
if(num < 0 && ans < num) ans = num;
if(num < ans) ans = num;
if(num > 0 && Math.abs(ans) >= num) ans = num;
}
return ans;
}
here is a method that gives you the nearest to zero.
use case 1 : {1,3,-2} ==> return 1 : use the Math.abs() for comparison and get the least.
use case 2 : {2,3,-2} ==> return 2 : use the Math.abs() for comparison and get the Math.abs(least)
use case 3 : {-2,3,-2} ==> return -2: use the Math.abs() for comparison and get the least.
public static double getClosestToZero(double[] liste) {
// if the list is empty return 0
if (liste.length != 0) {
double near = liste[0];
for (int i = 0; i < liste.length; i++) {
// here we are using Math.abs to manage the negative and
// positive number
if (Math.abs(liste[i]) <= Math.abs(near)) {
// manage the case when we have two equal neagative numbers
if (liste[i] == -near) {
near = Math.abs(liste[i]);
} else {
near = liste[i];
}
}
}
return near;
} else {
return 0;
}
}
You can do like this:
String res = "";
Arrays.sort(arr);
int num = arr[0];
int ClosestValue = 0;
for (int i = 0; i < arr.length; i++)
{
//for negatives
if (arr[i] < ClosestValue && arr[i] > num)
num = arr[i];
//for positives
if (arr[i] > ClosestValue && num < ClosestValue)
num = arr[i];
}
res = num;
System.out.println(res);
First of all you need to store all your numbers into an array. After that sort the array --> that's the trick who will make you don't use Math.abs(). Now is time to make a loop that iterates through the array. Knowing that array is sorted is important that you start to make first an IF statement for negatives numbers then for the positives (in this way if you will have two values closest to zero, let suppose -1 and 1 --> will print the positive one).
Hope this will help you.
The easiest way to deal with this is split the array into positive and negative sort and push the first two items from both the arrays into another array. Have fun!
function closeToZeroTwo(arr){
let arrNeg = arr.filter(x => x < 0).sort();
let arrPos = arr.filter(x => x > 0).sort();
let retArr = [];
retArr.push(arrNeg[0], arrPos[0]);
console.log(retArr)
}
Easiest way to just sort that array in ascending order suppose input is like :
int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};
then after sorting it will gives output like:
{-5,-4,2,5,7,10,12,28,45,65,85,95,}
and for positive integer number, the Closest Positive number is: 2
Logic :
public class Closest {
public static int getClosestToZero(int[] a) {
int temp=0;
//following for is used for sorting an array in ascending nubmer
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if (a[j]>a[j+1]) {
temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
//to check sorted array with negative & positive values
System.out.print("{");
for(int number:a)
System.out.print(number + ",");
System.out.print("}\n");
//logic for check closest positive and Integer
for (int i = 0; i < a.length; i++) {
if (a[i]<0 && a[i+1]>0) {
temp = a[i+1];
}
}
return temp;
}
public static void main(String[] args) {
int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};
int closets =getClosestToZero(array);
System.out.println("The Closest Positive number is : "+closets);
}
}
static void closestToZero(){
int[] arr = {45,-4,-12,-2,7,4};
int max = Integer.MAX_VALUE;
int closest = 0;
for (int i = 0; i < arr.length; i++){
int value = arr[i];
int abs = Math.abs(value);
if (abs < max){
max = abs;
closest = value;
}else if (abs == max){
if (value > closest){
closest = value;
}
}
}
Return a positive integer if two absolute values are the same.
package solution;
import java.util.Scanner;
public class Solution {
public static void trier(int tab[]) {
int tmp = 0;
for(int i = 0; i < (tab.length - 1); i++) {
for(int j = (i+1); j< tab.length; j++) {
if(tab[i] > tab[j]) {
tmp = tab[i];
tab[i] = tab[j];
tab[j] = tmp;
}
}
}
int prochePositif = TableauPositif(tab);
int procheNegatif = TableauNegatif(tab);
System.out.println(distanceDeZero(procheNegatif,prochePositif));
}
public static int TableauNegatif(int tab[]) {
int taille = TailleNegatif(tab);
int tabNegatif[] = new int[taille];
for(int i = 0; i< tabNegatif.length; i++) {
tabNegatif[i] = tab[i];
}
int max = tabNegatif[0];
for(int i = 0; i <tabNegatif.length; i++) {
if(max < tabNegatif[i])
max = tabNegatif[i];
}
return max;
}
public static int TableauPositif(int tab[]) {
int taille = TailleNegatif(tab);
if(tab[taille] ==0)
taille+=1;
int taillepositif = TaillePositif(tab);
int tabPositif[] = new int[taillepositif];
for(int i = 0; i < tabPositif.length; i++) {
tabPositif[i] = tab[i + taille];
}
int min = tabPositif[0];
for(int i = 0; i< tabPositif.length; i++) {
if(min > tabPositif[i])
min = tabPositif[i];
}
return min;
}
public static int TailleNegatif(int tab[]) {
int cpt = 0;
for(int i = 0; i < tab.length; i++) {
if(tab[i] < 0) {
cpt +=1;
}
}
return cpt;
}
public static int TaillePositif(int tab[]) {
int cpt = 0;
for(int i = 0; i < tab.length; i++) {
if(tab[i] > 0) {
cpt +=1;
}
}
return cpt;
}
public static int distanceDeZero(int v1, int v2) {
int absv1 = v1 * (-1);
if(absv1 < v2)
return v1;
else if(absv1 > v2)
return v2;
else
return v2;
}
public static void main(String[] args) {
int t[] = {6,5,8,8,-2,-5,0,-3,-5,9,7,4};
Solution.trier(t);
}
}
To maintain O(n) time complexity and getting the desired results we have to add another variable called 'num' and assign to it 'near' before changing it's value. And finally make necessary checks. The improvements in the code are are:
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
int num=near;
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
num=near;
near = data[i];
}
}
if(near<0 && near*(-1)==num)
near=num;
System.out.println( near );
}
}
We have to find the Closest number to zero.
The given array can have negative values also.
So the easiest approach would append the '0' in the given array and sort it and return the element next to '0'
append the 0
Sort the Array
Return the element next to 0.
`
N = int(input())
arr = list(map(int, input().split()))
arr.append(0)
arr.sort()
zeroIndex = arr.index(0)
print(arr[zeroIndex + 1])
--> If this solution leaves corner cases please let me know also.
`
if you don't wanna use the inbuilt library function use the below code (just an and condition with your existing code)-
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2,-1,1};
int curr = 0;
int near = data[0];
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
curr = data[i] * data[i];
if ( curr <= (near * near) && !((curr - (near * near) == 0) && data[i] < 0)) {
near = data[i];
}
}
System.out.println( near );
}
}
!((curr - (near * near) == 0) && data[i] < 0) : skip asignment if if near and curr is just opposit in sign and the curr is negative
public static int find(int[] ints) {
if (ints==null) return 0;
int min= ints[0]; //a random value initialisation
for (int k=0;k<ints.length;k++) {
// if a positive value is matched it is prioritized
if (ints[k]==Math.abs(min) || Math.abs(ints[k])<Math.abs(min))
min=ints[k];
}
return min;
}
public int check() {
int target = 0;
int[] myArray = { 40, 20, 100, 30, -1, 70, -10, 500 };
int result = myArray[0];
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] == target) {
result = myArray[i];
return result;
}
if (myArray[i] > 0 && result >= (myArray[i] - target)) {
result = myArray[i];
}
}
return result;
}
I have added a check for the positive number itself.
Please share your views folks!!
public class ClosesttoZero {
static int closZero(int[] ints) {
int result=ints[0];
for(int i=1;i<ints.length;i++) {
if(Math.abs(result)>=Math.abs(ints[i])) {
result=Math.abs(ints[i]);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ints= {1,1,5,8,4,-9,0,6,7,1};
int result=ClosesttoZero.closZero(ints);
System.out.println(result);
}
}
It can be done simply by making all numbers positive using absolute value then sort the Array:
int[] arr = {9, 1, 4, 5, 6, 7, -1, -2};
for (int i = 0; i < arr.length; ++i)
{
arr[i] = Math.abs(arr[i]);
}
Arrays.sort(arr);
System.out.println("Closest value to 0 = " + arr[0]);
import java.math.*;
class Solution {
static double closestToZero(double[] ts) {
if (ts.length == 0)
return 0;
double closestToZero = ts[0];
double absClosest = Math.abs(closestToZero);
for (int i = 0; i < ts.length; i++) {
double absValue = Math.abs(ts[i]);
if (absValue < absClosest || absValue == absClosest && ts[i] > 0) {
closestToZero = ts[i];
absClosest = absValue;
}
}
return closestToZero;
}
}
//My solution priorizing positive numbers contraint
int closestToZero = Integer.MAX_VALUE;//or we
for(int i = 0 ; i < arrayInt.length; i++) {
if (Math.abs(arrayInt[i]) < closestToZero
|| Math.abs(closestToZero) == Math.abs(arrayInt[i]) && arrayInt[i] > 0 ) {
closestToZero = arrayInt[i];
}
}

How can I find the smallest covering prefix of an array in Java?

Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println 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
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}

Categories