↓ Skip to main content
Java

Smallest Integer

·1 min
Table of Contents

Code available here.

The ask was to identify the smallest possible integer (> 0) in the array of integers.

Example
#

1. [-1,2] -> 1
2. [-1,-2] -> 1
3. [1,3] -> 2

I was initially thinking of using sets and then finding out the missing one, but then reaized it is simpler and I do not need sets

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        int smallestInt = 1;
        if(A.length == 0) return smallestInt;
        // Sort
        Arrays.sort(A);

        // If the first element is greater than 1
        if(A[0] > 1) return smallestInt;

        //If the last element is less than 1
        if(A[ A.length - 1] <= 0 ) return smallestInt;
    
        //Iterate through the array and process
        for(int i = 0; i < A.length; i++){
            if(A[i] == smallestInt){
                smallestInt++;}
        }

        return smallestInt;
    }
}
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Fortune v1.0

·4 mins
In one of recent discussions with Mr. X I was asked about my approach to solving the Linux cookie problem A random quote Repository will be a text file Each quote will be segregated by a '%' Can be multiline. I always believe in incremental steps so here is what I could think of

Nth Prime

·2 mins
Prime number is an age old problem. I am trying to solve it via streams. class PrimeCalculator { public int nth(int nth) { if (nth <= 0) throw new IllegalArgumentException(); // Will skip the nth - 1 // 2 to n-1 return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt(); } public static boolean isPrime(int x) { // till half of x return IntStream.rangeClosed(2, (int) (x/2) ).dropWhile(i -> x % i != 0).findFirst().isEmpty(); } } Explanation # public int nth(int nth) { if (nth <= 0) throw new IllegalArgumentException(); // Will skip the nth - 1 // 2 to n-1 return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt(); } The method nth(int) allows you to return the nth prime starting at 2, 3, 5....

JavaStream: Characters

·1 min
Continuing from the last blog how about checking a pangram using streams. public class PangramChecker { private String allChars = "abcdefghijklmnopqrstuvwxyz"; public boolean isPangram(String input) { if (input.length() <= 0 || input.isBlank()){ return false; } return (allChars.chars().map(x -> (char) x).filter(x -> input.toLowerCase().indexOf(x) >= 0).count() == 26); } } All the for loops have been squeezed into a simple line