Skip to main content

Posts

Showing posts with the label interview

Prime Anagrams - Comparing Anagrams using Prime Numbers

Introduction In this post, we will use prime numbers to compare anagrams. We will assign the prime number to each character in a string and then multiply them. Two strings will be equal if their product is the same. Implementation in Java public class PrimeAnagram { static int [] alphaPrime = {5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107}; static String alphabets = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println(isPrimeAnagram("parse", "spare")); } private static boolean isPrimeAnagram(String value1,String value2) { return getPrime(value1) == getPrime(value2); } private static int getPrime(String value) { value = value.toLowerCase(); int productValue = 1; for(int index = 0; index < value.length(); index++) { productValue *= alphaPrime[ alphabets.indexOf(value.charAt(index)) ]; } return productValue; } } Conclusion We

Often asked interview question to write code of Singleton Pattern?

Introduction I have been often asked this question in an interview to write a code of Singleton pattern. I have noticed that developers have the knowledge of what is Singleton pattern but often they forget the key points regarding its implementation. In this post, I will highlight the key points to remember for your upcoming interview. Implementation public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } Key Points to remember a) instance is declared as private and static  b) The constructor is declared as private c) getInstance method is static and synchronized to make it thread free Conclusion In this post, we learned how to implement the Singleton pattern using Java language. We have also noted down the key points to remember.Please leave your comments in the comments box.

Solution of popular FizzBuzz coding puzzle in Java language

Introduction FizzBuzz is one of the popular coding puzzles asked in a programming interview. In this post, we will learn its implementation using Java 8. Problem We have 1 to n Integers. Write a program that iterates over these integers, print Fizz if Integer is multiple of 3, print Buzz if Integer is multiple of 5, print FizzBuzz if Integer is multiple of both 3 and 5 else print the Integer.  Solution import java.util.stream.IntStream; public class FizzBuzz { public static void main(String[] args) { int n = 100; IntStream.range(1, n).forEach( i -> { /* if( i % 3 == 0 && i % 5 == 0 ) is equivalent to i % 15 == 0 * and will reduce lines of code */ if( i % 15 == 0) { System.out.println("FizzBuzz"); }else if ( i % 3 == 0) { System.out.println("Fizz"); }else if ( i % 5 == 0) { System.out.println("Buzz"); }else { System.out.println(i); } }); } } Note that multiple of 15 is mult