Skip to content

Instantly share code, notes, and snippets.

@sm2774us
Created September 10, 2023 03:10
Show Gist options
  • Save sm2774us/55c2b592c565daae23c3e331fe130de6 to your computer and use it in GitHub Desktop.
Save sm2774us/55c2b592c565daae23c3e331fe130de6 to your computer and use it in GitHub Desktop.
Codility Solutions in Java

#Binary Gap

class Solution {
	public int solution2(int n) { 
		// get rid of right-hand zeros
	    while (n != 0 && (n & 1) == 0) {
	        n >>>= 1;
	    }
	    System.out.println("n--->"+n);
	    
	    int max = 0;
	    int gap = 0;
	    while (n != 0) {
	        if ((n & 1) == 0) {
	            gap++;
	            max = Math.max(gap, max);
	        } else {
	            gap = 0;
	        }
	        n >>>= 1;
	    }
	    return max;
	}
}

#Cyclic Rotation

import java.util.Arrays;
import java.util.LinkedList;
import java.util.stream.Collectors;

class Solution {
    /**
     * Solution 1:
     * Java solution using the concept of "mod" (to make it cyclic)
     */
    public int[] solution1(int[] A, int K) {
        // Using the concept of "mod" (to make it cyclic)
        
        int[] new_array = new int[A.length]; // a new array
        
        for(int i=0; i< A.length; i++){
            int new_position = (i + K) % A.length; // using "mod" to do Cyclic Rotation           
            new_array[new_position] = A[i]; // put A[i] to the new position
        }
        
        return new_array; // return new array
    }
    
    /**
     *  Solution 2:
     *  Java8 Stream Solution
     */
    public int[] solution2(int[] A, int K) {
        if (A.length == 0) {
            return A;
        }

        final LinkedList<Integer> list = Arrays.stream(A)
                .boxed()
                .collect(Collectors.toCollection(LinkedList::new));

        while (K > 0) {
            list.addFirst(list.getLast());
            list.removeLast();
            K--;
        }

        return list.stream()
                .mapToInt(Integer::intValue)
                .toArray();
    }
}

#Odd Occurrences In Array

import java.util.HashSet;
import java.util.Set;

class Solution {

	/**
	 * Solution 1:
	 * XOR Solution
	 */
    public int solution1(int[] A) {
        // Using the concept of "XOR" (^)
        // when there is a pair A and B 
        // A^B will be zero 
        // A^B^C (where C is not paired), 
        // then A^B^C = C
        
        // special case
        if(A.length == 0)
            return 0;
        
        int unpaired;
        unpaired = A[0]; // initial
        
        for(int i=1; i< A.length; i++){    
            unpaired = unpaired ^ A[i]; // xor    
        }
        
        return unpaired; // return the unpaired value
    }

	/**
	 * Solution 2:
	 * Java Solution using HashSet Data Structure.
	 */
    public int solution2(final int[] A) {

        final Set<Integer> set = new HashSet<>();

        for (int i : A) {
            if (!set.add(i)) {
                set.remove(i);
            }
        }

        return set.iterator().next();
    }
}

#FrogJmp

class Solution {
    public int solution(int X, int Y, int D) {
        // write your code in Java SE 8
        if(X>=Y) return 0;
        return (Y-X)%D==0?(Y-X)/D:(Y-X)/D +1;
    }
}

# PermMissingElem

import java.util.Arrays;

class Solution {


	private long calcSum(int[] A) {
        long sum = 0;
        
        for(int elem: A) { sum += elem; }
        
        return sum;
    }

	/**
	 * Solution 1:
	 */
    public int solution1(int[] A) {
        // since all distinct, we are safe.. some controls can be omitted
        // if the missing also available, sum would be n (n + 1) / 2 where n = length (A) + 1
        // tip: sums should be long, since might overflow for large n
        long shouldBeLength = A.length + 1;
        long shouldBeSum = shouldBeLength * (shouldBeLength + 1) / 2;
        
        return (int) (shouldBeSum - calcSum(A));   
    }

	/**
	 * Solution 2:
     * Using the concept of "Sum = (ceiling + floor) * height /2"
	 */
    public int solution2(int[] A) {
        // Using the concept of "Sum = (ceiling + floor) * height /2"
        // So---> Sum = (1 + N+1) * N /2
        // the missing element can be found by minus other elements
        
        // note: need to use "long" to avoid potential bugs (large numbers)
        long ceiling = A.length +1;
        long floor = 1;
        long height = A.length + 1; // note: need to plus extra "1" 
                                    // because there is one element "missing"! 
                                    // be careful about this (important)
        long sum = (ceiling +floor) * height /2; // main idea
        /*        
        int high = A.length +1; 
        int low = 1;
        int height = A.length + 1; 
        int sum = (high +low) * height /2; // main idea
        */
        long missing_number = sum; // initial setting (sum)
        
        for(int i=0; i<A.length; i++){
            missing_number = missing_number - A[i]; // minus other elements
        }
        
        return (int)missing_number; // return the missing element (long->int)
    }

	/**
	 * Solution 3:
     * Java8 Stream Solution
	 */
	public int solution3(int[] A) {
		if(A == null){
			return 0;
		}
		long arraySum = Arrays.stream(A).asLongStream().sum();
		long N = A.length+1;
		long expectedSum = (N*(N+1))/2;
        return (int)(expectedSum-arraySum);
    }

	public static void main(String[] args) {
		PermMissingElem permMissingElem = new PermMissingElem();		
		int[] input = {2,3,1,5};
		int result1 = permMissingElem.solution1(input);
		System.out.println("result1--->"+result1);
		
		int result2 = permMissingElem.solution2(input);
		System.out.println("result2--->"+result2);

		int result3 = permMissingElem.solution3(input);
		System.out.println("result3--->"+result3);
	}
}

#PermCheck

import java.util.*;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
           long N = A.length,sum=0;
        Set<Integer> set = new HashSet();
        for(int i=0;i<A.length;i++){
    	 if(!set.contains(A[i])) {set.add(A[i]);sum += A[i];}
     }
     if(N*(N+1)/2==sum) return 1;
    return 0;
    }
}

#MissingInteger

// you can also use imports, for example:
import java.util.*;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
         int b=0;
        Set<Integer> set = new LinkedHashSet();
        for(int i=1;i<=A.length;i++){
           set.add(i);
        }
        for(int i=0;i<A.length;i++){
           
    	 if(set.contains(A[i])) {set.remove(A[i]);}
     }
     for(Integer a: set){ b = a; break;}
     return b==0?A.length+1:b;
    }
}

#FrogRiverOne

import java.util.*;
class Solution {
    public int solution(int X, int[] A) {
        // write your code in Java SE 8
        Set<Integer> set = new LinkedHashSet();
        int i;
        for(i=1;i<=X;i++){
            set.add(i);
    }
    for(i=0;i<A.length;i++){
        if(set.contains(A[i])) set.remove(A[i]);
        if(set.size()==0) break;
}
 return set.size()==0?i:-1;
}
}

#[CountDiv]

class Solution {
    public int solution(int A, int B, int K) {
        // write your code in Java SE 8
        int count = 0;
        count = B/K - A/K;
        if(A%K==0)count++;
        return count; 
    }
}

#Distinct

import java.util.*;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        Set<Integer> set = new HashSet();
        for(int i=0;i<A.length;i++){
            set.add(A[i]);
    }
    return set.size();
}
}

#MaxProductOfThree

import java.util.*;

// 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 N = A.length;
        Arrays.sort(A);
    return Math.max(A[0]*A[1]*A[N-1],A[N-1]*A[N-2]*A[N-3]);
}
}

#Triangle

import java.util.*;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        Arrays.sort(A);
        int N = A.length,i;
        for(i=0;i<N-2;i++){
            long a,b,c;
            a = A[i]+A[i+1];
            b = A[i+2]+A[i+1];
            c = A[i]+A[i+2];
            if(a>A[i+2] && b >A[i] && c>A[i+1]) return 1;
    }
    return 0;
}
}

#Brackets

import java.util.*;
class Solution {
    public int solution(String S) {
        // write your code in Java SE 8
      Stack<Character> st = new Stack();
      int i;
      char ch;
      for(i=0;i<S.length();i++){
          ch = S.charAt(i);
          if(ch=='('||ch=='['||ch=='{'||ch=='V') st.push(ch);
          else if(ch==')'||ch==']'||ch=='}' ||ch=='W'){
              if(st.isEmpty()|| (ch==')'&& st.peek()!='(')||(ch==']'&&st.peek()!='[') 
              || (ch=='}' && st.peek()!='{') || (ch=='W' && st.peek()!='V')) return 0;
              st.pop();
                 
              }
    }
      return st.isEmpty()?1:0;  
}
}

#Dominator

import java.util.*;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        HashMap<Integer,Integer> map = new HashMap();
        int i,dominator=0,count=0;
        for(i=0;i<A.length;i++){
            if(map.containsKey(A[i])){
                map.put(A[i],map.get(A[i])+1);
            }else{
                map.put(A[i],1);
            }
        }    
    for(Integer a:map.keySet()){
    
        if(map.get(a)>count){
        count = map.get(a);
        dominator = a;
        }
    }
    for(i=0;i<A.length;i++){
        if(dominator==A[i]&&count>A.length/2) return i;
    }
    return -1;
}
}

#Nesting

import java.util.*;
class Solution {
    public int solution(String S) {
        // write your code in Java SE 8
      Stack<Character> st = new Stack();
      int i;
      char ch;
      for(i=0;i<S.length();i++){
          ch = S.charAt(i);
          if(ch=='('||ch=='V') st.push(ch);
          else if(ch==')'||ch=='W'){
              if(st.isEmpty()|| (ch==')'&& st.peek()!='(') || (ch=='W' && st.peek()!='V')) return 0;
              st.pop();

              }
    }
      return st.isEmpty()?1:0;  
}
}

#CountFactors

class Solution {
    public int solution(int N) {
        int count = 0;
       for(int i=1;i<(int)((Math.ceil(Math.sqrt(N))));i++){
           if(N%i==0) count++;
       }
       return count*2+((int)((Math.ceil(Math.sqrt(N))))==(int)(Math.sqrt(N))?1:0);
    }
}

#MinPerimeterRectangle

class Solution {
    public int solution(int N) {
        int min = Integer.MAX_VALUE;
        for(int i=1;i<=(int)(Math.ceil(Math.sqrt(N)));i++){
            if(N%i==0){
                min = Math.min(min,2*(N/i+i));
            }
        }
        return min;
    }
}

#CountSemiPrimes Pending

import java.util.*;
class Solution {
    public int[] solution(int N, int[] P, int[] Q) {
       boolean arr[] = new boolean[N+1],flag;
       int i,j,k,count=0;
       if(N>1) arr[0] = arr[1] = true;
       for(i=2;i<=(int)Math.sqrt(arr.length-1);i++){
       if(!arr[i]){
           for(j=i*i;j<=arr.length-1;j+=i){
               arr[j] = true;
           }
       }
    }
    int[] res = new int[P.length];
    for(i=0;i<P.length;i++){
        count = 0;
        for(j=P[i];j<=Q[i];j++){
            flag = false;
            if(arr[j]&&j>2){
            for(k=2;k<=(int)Math.sqrt(j);k++){
                if(!arr[k] && j%k==0&&!arr[j/k]) {flag = true;break;} 
                    }
                    if(flag) count++;
                }
                res[i] = count;
        }
    }
        return res;
    }
}

#[CountNonDivisible]

class Solution {
    public int[] solution(int[] A) {
       int i,j,count;
       int[] B = new int[A.length]; 
       for(i=0;i<A.length;i++){
           count = 0;
           for(j=0;j<A.length;j++){
               if(A[i]%A[j]!=0) count++;
           }
           B[i] = count;
       }
       return B;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment