import java.util.*;
class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
class BST {
public static boolean search(Node root, int key) {
if(root == null) {
return false;
}
while(root != null) {
if(root.value == key) {
return true;
}
if(root.value > key) {
root = root.left;
} else if(root.value < key) {
root = root.right;
}
}
return false;
}
}
import org.junit.*;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
Node root;
@Before
public void setUp() {
root = new Node(10);
Node B = new Node(5);
Node C = new Node(15);
Node D = new Node(4);
Node E = new Node(6);
Node F = new Node(12);
Node G = new Node(17);
root.left = B;
root.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
}
@Test
public void testSomething() {
assertEquals(BST.search(root, 4), true);
}
@Test
public void testSomething2() {
assertEquals(BST.search(root, 16), false);
}
@Test
public void testSomething3() {
assertEquals(BST.search(root, 12), true);
}
@Test
public void testSomething4() {
assertEquals(BST.search(root, 17), true);
}
@Test
public void testSomething5() {
assertEquals(BST.search(root, 8), false);
}
}
This is a test kumite
var getAge = function(today, dob) {
if(!today || !dob) {
return null;
}
var now = new Date(today);
return now.getYear() - new Date(dob).getYear();
};
// You can also use Chai (http://chaijs.com/) by requiring it yourself
var expect = require("chai").expect;
describe("getAge", function(){
it("should return 10 for 2016/10/20 and 2006/10/20", function(){
expect( getAge('2016/10/20', '2006/10/20') ).to.equal( 10 );
});
it("should return null for blank today", function(){
expect( getAge('', '2006/10/20') ).to.be.null;
});
it("should return null for blank dob", function(){
expect( getAge('2016/10/20', '') ).to.be.null;
});
it("should return null for blank dates", function(){
expect( getAge('', '') ).to.be.null;
});
it("should return null for unparseable today date", function(){
expect( getAge('what', '') ).to.be.null;
});
it("should return null for unparseable dob", function(){
expect( getAge('', 'what') ).to.be.null;
});
});
Given a list of numbers, return the combination that is largest number.
As output can be large, return the result in String
format.
Example:
Input:
[5, 50, 56]
Output:
56550
import java.util.*;
class Solution {
public static String largestNumber(Integer[] nums) {
Arrays.sort( nums, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
String aStr = a.toString();
String bStr = b.toString();
return (aStr + bStr).compareTo(bStr + aStr) * -1;
}
} );
String result = "";
for(Integer num : nums) {
result += num.toString();
}
return result;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void test1() {
assertEquals( "56550", Solution.largestNumber(new Integer[] {5, 50, 56}) );
}
@Test
public void test2() {
assertEquals( "8765431", Solution.largestNumber(new Integer[] {1, 3, 5, 4, 7, 6, 8}) );
}
}
Given array of integer elements, find the index of peak element in O(Log N)
time complexity.
A peak element is an element that is greater than its neighbors. Given an input array where num[i] != num[i + 1]
, find a peak element and return its index. Array may contain multiple peaks, in that case return index of any peak.
Example:
Input:
1 2 3 1
Output:
2
because peak element is 3
and it is at index 2
.
import java.util.*;;
class Solution {
public static int peakIndex(int[] nums) {
int left = 0;
int right = nums.length - 1;
int peak = -1;
while(left <= right) {
if(left == right) {
peak = left;
break;
}
int mid = (left + right) / 2;
if(nums[mid] < nums[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return peak;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void test1() {
assertEquals(2, Solution.peakIndex(new int[] {1, 2, 3, 1}));
}
@Test
public void test2() {
assertEquals(1, Solution.peakIndex(new int[] {1, 2, 1}));
}
@Test
public void test3() {
assertEquals(0, Solution.peakIndex(new int[] {2}));
}
@Test
public void test4() {
assertEquals(4, Solution.peakIndex(new int[] {1, 2, 3, 4, 5, 4, 3, 2}));
}
@Test
public void test5() {
assertEquals(14, Solution.peakIndex(new int[] {1, 2, 3, 2, 1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7, 6, 5, 4, 3, 7, 8, 1}));
}
}
Write a program to find if given array contains duplicate elements or all elements are unique.
Your function should output true
if there are duplicates, false
if all elements are unique.
Example:
Input:
1 4 3 2 6 4
Output:
true
Input:
1 4 3 2 6 5
Output:
false
import java.util.*;
class Solution {
/**
* Checks if given array contains duplicate elements.
* Complexity: O(N)
* @author Jayesh Chandrapal
* @param nums integer array of elements
* @return true if duplicate elements are found, false otherwise
*/
public static boolean hasDuplicates(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0, len = nums.length; i < len; i++) {
if(set.contains(nums[i])) {
return true;
} else {
set.add(nums[i]);
}
}
return false;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void test1() {
assertEquals( true, Solution.hasDuplicates(new int[]{1, 2, 3, 4, 4}) );
}
@Test
public void test2() {
assertEquals( false, Solution.hasDuplicates(new int[]{1, 2, 3, 4, 5}) );
}
@Test
public void test3() {
assertEquals( false, Solution.hasDuplicates(new int[]{1}) );
}
@Test
public void test4() {
assertEquals( false, Solution.hasDuplicates(new int[]{-1, 5, -3, 3}) );
}
@Test
public void test5() {
assertEquals( false, Solution.hasDuplicates(new int[]{}) );
}
@Test
public void test6() {
assertEquals( true, Solution.hasDuplicates(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 1}) );
}
}
Given an expression string exp, examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp.
For example, the program should return true
for [()]{}{[()()]()}
and false
for [(])
.
Check provided test cases to see expected behaviour for different inputs.
/**
* Check if brackets are matching.
* Time Complexity: O(N), Space Complexity: O(N)
*
* @author Jayesh Chandrapal
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class MatchingBrackets {
/**
* Checks if given input string contains matching brackets.
*
* @params str input string to be checked
* @returns boolean value indicating if given string contains matching brackets
*/
public static boolean isBalanced(String str) {
boolean balanced = true;
Stack<Character> stack = new Stack<Character>();
for(Character c : str.toCharArray()) {
if(c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if(stack.isEmpty()) {
balanced = false;
break;
}
Character top = stack.peek();
if((c == ')' && top == '(') || (c == '}' && top == '{') || (c == ']' && top == '[')) {
stack.pop();
} else {
balanced = false;
break;
}
}
}
return balanced && stack.isEmpty();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TestCases {
@Test
public void test1() {
assertTrue( MatchingBrackets.isBalanced("{([])}") );
}
@Test
public void test2() {
assertTrue( MatchingBrackets.isBalanced("{}()[]") );
}
@Test
public void test3() {
assertFalse( MatchingBrackets.isBalanced("{([})}") );
}
@Test
public void test4() {
assertFalse( MatchingBrackets.isBalanced("(") );
}
@Test
public void test5() {
assertFalse( MatchingBrackets.isBalanced("{") );
}
@Test
public void test6() {
assertFalse( MatchingBrackets.isBalanced("[") );
}
@Test
public void test7() {
assertFalse( MatchingBrackets.isBalanced(")") );
}
@Test
public void test8() {
assertFalse( MatchingBrackets.isBalanced("}") );
}
@Test
public void test9() {
assertFalse( MatchingBrackets.isBalanced("]") );
}
@Test
public void test10() {
assertTrue( MatchingBrackets.isBalanced("{([{{([{}()[]])}}({([{{([{{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}]])}]])}") );
}
@Test
public void test11() {
assertTrue( MatchingBrackets.isBalanced("") );
}
}
Write a function that determines if given number is a power of two. A power of two means a number of the form 2^n
where n
is an integer, i.e. the result of exponentiation with number two as the base and integer n
as the exponent. i.e. 1024 is a power of two: it is 2^10
.
Example:
power_of_two(4096) # true
power_of_two(333) # false
def power_of_two( n ):
return n & ( n - 1 ) == 0
from random import randint
for x in range(5):
n = 2 ** randint( 21, 25 )
test.assert_equals( power_of_two(n), True )
for x in range(5):
n = 2 ** randint( 21, 25 )+(-1) ** randint( 1, 4 )
test.assert_equals( power_of_two(n), False )
Implementation of Merge Sort.
-
Time Complexity:
O(n log(n))
-
Space Complexity:
O(n)
-
Preserves the input order of equal elements in the sorted output.
-
Type of Divide-and-Conquer algorithm.
-
Efficient at handling slow-to-access sequential media.
-
Well-suited for sorting huge amounts of data that does not fit into memory.
-
Wiki Link: Merge Sort
class Sort:
def merge_sort(self, nums):
if nums == None: return None
if len(nums) > 1:
mid = len(nums) // 2
lefthalf = nums[:mid]
righthalf = nums[mid:]
self.merge_sort(lefthalf)
self.merge_sort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nums[k] = lefthalf[i]
i += 1
else:
nums[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
nums[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
nums[k] = righthalf[j]
j += 1
k += 1
return nums
# Test sorting
sortApp = Sort()
test.describe("Testing normal sort ..")
nums = [6,3,4,5,1,2,9,8,7]
expected = [1,2,3,4,5,6,7,8,9]
Test.assert_equals(sortApp.merge_sort(nums), expected, "Failed normal sorting")
# Test sorting long list
test.describe("Testing long list ..")
nums = [1,5,4,6,5,7,6,8,7,9,8,0,2,3,4,5,6,7,2,5,3,4,1,6,5,8,7,9,8,0,2,4,3,5,4,6,5,7,7,6,8,9,5,7,6,3,4,2,3,1,6,5,8,6,7,9,8,0,5,6,4,5,3,4,2,6,4,7,5,8,6,9,7,0,1,4,3,5,4,6,5,8,7,9,3,7,5,6,1,9,0,4,7,6,1,8,3,6,0,9,4,7,6,8,1,4,3,5,4,6,5,7,6,8,7,9,8,0,2,5,4,7,5,8,6,9,7,0,8,9,7,8,6,7,5,6,4,5,3,4,3,4,1,3,2,4,3,5,4,6,5,7,6,8,7,8,1,3,2,4,3,5,4,6,5,7,6,8,6,8,6,7,56,7,5,6,4,5,34,5,4,6,5,7,6,6,8,6,8]
expected = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 34, 56]
Test.assert_equals(sortApp.merge_sort(nums), expected, "Failed sorting long list")
# Test None as input
test.describe("Testing with None as input ..")
Test.assert_equals(sortApp.merge_sort(None), None, "Failed None as input")
# Test all elements same
test.describe("Testing same elements in list ..")
nums = [4,4,4,4,4]
expected = [4,4,4,4,4]
Test.assert_equals(sortApp.merge_sort(nums), expected, "Failed same elements")
# Test negatives
test.describe("Testing negative numbers ..")
nums = [-1,-2,-6,-3,-4,-5,-9,-8,-7]
expected = [-9,-8,-7,-6,-5,-4,-3,-2,-1]
Test.assert_equals(sortApp.merge_sort(nums), expected, "Failed negative numbers")
Implementation of Insertion Sort.
-
Time Complexity: Worst case:
O(n^2)
, Best case:O(n)
-
Space Complexity:
O(1)
-
Useful when list size is small.
-
only scans as many elements as needed to determine the correct location.
-
More efficient than bubble or selection sort.
-
Efficient for data sets that are already substantially sorted.
-
Requires more writes because the inner loop can require shifting large sections of the sorted portion of the array.
-
Can sort a list as it receives it.
-
Wiki Link: Insertion Sort
class Sort:
def insertion_sort(self, nums):
if nums is None:
return None
for i in range(1, len(nums)):
currentvalue = nums[i]
position = i
while position > 0 and nums[position - 1] > currentvalue:
nums[position] = nums[position - 1]
position -= 1
nums[position] = currentvalue
return nums
# Test sorting
sortApp = Sort()
test.describe("Testing normal sort ..")
nums = [6,3,4,5,1,2,9,8,7]
expected = [1,2,3,4,5,6,7,8,9]
Test.assert_equals(sortApp.insertion_sort(nums), expected, "Failed normal sorting")
# Test sorting long list
test.describe("Testing long list ..")
nums = [1,5,4,6,5,7,6,8,7,9,8,0,2,3,4,5,6,7,2,5,3,4,1,6,5,8,7,9,8,0,2,4,3,5,4,6,5,7,7,6,8,9,5,7,6,3,4,2,3,1,6,5,8,6,7,9,8,0,5,6,4,5,3,4,2,6,4,7,5,8,6,9,7,0,1,4,3,5,4,6,5,8,7,9,3,7,5,6,1,9,0,4,7,6,1,8,3,6,0,9,4,7,6,8,1,4,3,5,4,6,5,7,6,8,7,9,8,0,2,5,4,7,5,8,6,9,7,0,8,9,7,8,6,7,5,6,4,5,3,4,3,4,1,3,2,4,3,5,4,6,5,7,6,8,7,8,1,3,2,4,3,5,4,6,5,7,6,8,6,8,6,7,56,7,5,6,4,5,34,5,4,6,5,7,6,6,8,6,8]
expected = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 34, 56]
Test.assert_equals(sortApp.insertion_sort(nums), expected, "Failed sorting long list")
# Test None as input
test.describe("Testing with None as input ..")
Test.assert_equals(sortApp.insertion_sort(None), None, "Failed None as input")
# Test all elements same
test.describe("Testing same elements in list ..")
nums = [4,4,4,4,4]
expected = [4,4,4,4,4]
Test.assert_equals(sortApp.insertion_sort(nums), expected, "Failed same elements")
# Test negatives
test.describe("Testing negative numbers ..")
nums = [-1,-2,-6,-3,-4,-5,-9,-8,-7]
expected = [-9,-8,-7,-6,-5,-4,-3,-2,-1]
Test.assert_equals(sortApp.insertion_sort(nums), expected, "Failed negative numbers")
Implementation of Selection Sort.
- Time Complexity:
O(n^2)
- Space Complexity:
O(1)
- Useful when list size is small
- Preferable to insertion sort in terms of number of writes (
O(n)
swaps versusO(n2)
swaps), it almost always far exceeds (and never beats) the number of writes that cycle sort makes, as cycle sort is theoretically optimal in the number of writes. This can be important if writes are significantly more expensive than reads, such as with EEPROM or Flash memory, where every write lessens the lifespan of the memory. - Wiki Link: Selection Sort
class Sort:
def selection_sort(self, nums):
if nums == None: return None
for i in range(0, len(nums) - 1):
minIndex = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[minIndex]:
minIndex = j
nums[i], nums[minIndex] = nums[minIndex], nums[i]
return nums
# Test sorting
sortApp = Sort()
test.describe("Testing normal sort ..")
nums = [6,3,4,5,1,2,9,8,7]
expected = [1,2,3,4,5,6,7,8,9]
Test.assert_equals(sortApp.selection_sort(nums), expected, "Failed normal sorting")
# Test sorting long list
test.describe("Testing long list ..")
nums = [1,5,4,6,5,7,6,8,7,9,8,0,2,3,4,5,6,7,2,5,3,4,1,6,5,8,7,9,8,0,2,4,3,5,4,6,5,7,7,6,8,9,5,7,6,3,4,2,3,1,6,5,8,6,7,9,8,0,5,6,4,5,3,4,2,6,4,7,5,8,6,9,7,0,1,4,3,5,4,6,5,8,7,9,3,7,5,6,1,9,0,4,7,6,1,8,3,6,0,9,4,7,6,8,1,4,3,5,4,6,5,7,6,8,7,9,8,0,2,5,4,7,5,8,6,9,7,0,8,9,7,8,6,7,5,6,4,5,3,4,3,4,1,3,2,4,3,5,4,6,5,7,6,8,7,8,1,3,2,4,3,5,4,6,5,7,6,8,6,8,6,7,56,7,5,6,4,5,34,5,4,6,5,7,6,6,8,6,8]
expected = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 34, 56]
Test.assert_equals(sortApp.selection_sort(nums), expected, "Failed sorting long list")
# Test None as input
test.describe("Testing with None as input ..")
Test.assert_equals(sortApp.selection_sort(None), None, "Failed None as input")
# Test all elements same
test.describe("Testing same elements in list ..")
nums = [4,4,4,4,4]
expected = [4,4,4,4,4]
Test.assert_equals(sortApp.selection_sort(nums), expected, "Failed same elements")
# Test negatives
test.describe("Testing negative numbers ..")
nums = [-1,-2,-6,-3,-4,-5,-9,-8,-7]
expected = [-9,-8,-7,-6,-5,-4,-3,-2,-1]
Test.assert_equals(sortApp.selection_sort(nums), expected, "Failed negative numbers")
Example:
Find first most frequently occuring number in given array.
Given input {1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2}
,
output should be 3
as it has highest frequency of occurence.
Note: This solution uses LinkedHashMap to preserve order of entry.
import java.util.*; /** Time Complexity : O(N) Space Complexity : O(N) */ class MaxOccurence { public static int findMax(int[] nums) { return findMaxOccurenceLinkedHashMap(nums); } private static int findMaxOccurenceLinkedHashMap(int[] nums) { int maxKey = 0, maxNum = 0; if(nums.length < 1) return -1; if(nums.length == 1) return nums[0]; Map<Integer, Integer> counts = new LinkedHashMap<Integer, Integer>(nums.length); for(int i = 0, len = nums.length; i < len; i++) { if(!counts.containsKey(nums[i])) { counts.put(nums[i], 1); } else { counts.put(nums[i], (counts.get(nums[i]) + 1)); } } for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { if (entry.getValue() > maxNum) { maxKey = entry.getKey(); maxNum = entry.getValue(); } } return maxKey; } }
- import java.util.*;
- /**
- Time Complexity : O(N)
- Space Complexity : O(N)
- */
- class MaxOccurence {
- public static int findMax(int[] nums) {
return findMaxOccurenceCountArray(nums);- return findMaxOccurenceLinkedHashMap(nums);
- }
private static int findMaxOccurenceCountArray(int[] nums) {int maxNum = 0;int maxCount = 0;- private static int findMaxOccurenceLinkedHashMap(int[] nums) {
- int maxKey = 0, maxNum = 0;
- if(nums.length < 1) return -1;
- if(nums.length == 1) return nums[0];
int[] counts = new int[nums.length];- Map<Integer, Integer> counts = new LinkedHashMap<Integer, Integer>(nums.length);
- for(int i = 0, len = nums.length; i < len; i++) {
counts[nums[i]]++;if(counts[nums[i]] > maxCount) {maxCount = counts[nums[i]];maxNum = nums[i];- if(!counts.containsKey(nums[i])) {
- counts.put(nums[i], 1);
- } else {
- counts.put(nums[i], (counts.get(nums[i]) + 1));
- }
- }
return maxNum;- for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
- if (entry.getValue() > maxNum) {
- maxKey = entry.getKey();
- maxNum = entry.getValue();
- }
- }
- return maxKey;
- }
- }
Example:
Find first most frequently occuring number in given array.
Given input {1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2}
,
output should be 3
as it has highest frequency of occurence.
import java.util.*;
/**
Time Complexity : O(N)
Space Complexity : O(N)
*/
class MaxOccurence {
public static int findMax(int[] nums) {
return findMaxOccurenceCountArray(nums);
}
private static int findMaxOccurenceCountArray(int[] nums) {
int maxNum = 0;
int maxCount = 0;
if(nums.length < 1) return -1;
if(nums.length == 1) return nums[0];
int[] counts = new int[nums.length];
for(int i = 0, len = nums.length; i < len; i++) {
counts[nums[i]]++;
if(counts[nums[i]] > maxCount) {
maxCount = counts[nums[i]];
maxNum = nums[i];
}
}
return maxNum;
}
}
import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class MaxOccurenceTest {
@Test
public void test1() {
int[] nums = {1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2};
assertEquals(3, MaxOccurence.findMax(nums));
}
@Test
public void test2() {
int[] nums = {5, 4, 6 ,7, 9, 8, 2, 4, 3, 6, 5, 8, 6, 1, 2, 5, 3, 4, 7, 9, 0, 8, 5, 7, 3, 4, 6, 1, 3};
assertEquals(5, MaxOccurence.findMax(nums));
}
@Test
public void test3() {
int[] nums = {8};
assertEquals(8, MaxOccurence.findMax(nums));
}
@Test
public void test4() {
int[] nums = {};
assertEquals(-1, MaxOccurence.findMax(nums));
}
@Test
public void test5() {
int[] nums = {2, 2, 3, 3, 4, 4, 5, 5, 6, 6};
assertEquals(2, MaxOccurence.findMax(nums));
}
@Test
public void test6() {
int[] nums = {2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
assertEquals(5, MaxOccurence.findMax(nums));
}
}
Using HashMap in Java.
/* HashMap Example */
import java.util.*;
import java.lang.*;
import java.io.*;
class HashMapDemo
{
public static void main (String[] args) throws java.lang.Exception
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 1);
map.put(3, 1);
map.put(4, 1);
map.put(5, 1);
map.put(6, 1);
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
int key = entry.getKey();
int value = entry.getValue();
System.out.println(key + " " + value);
}
}
}
Generate prime numbers within a given minimum and maximum.
min and max values should be positive (greater than 0).
import java.util.*;
public class Primes {
public static List<Integer> generatePrimes(int min, int max) {
List<Integer> primes = new ArrayList<Integer>();
boolean isPrime = false;
if((min > max) || min < 0 || max <= 0) {
return null;
}
for(int i = min; i <= max; i++) {
long endLimit = (long)Math.floor(Math.sqrt(i));
isPrime = true;
for(long j = 2; j <= endLimit; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
primes.add(i);
}
}
return primes;
}
}
import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class PrimesTest {
@Test
public void testCase1() {
List<Integer> expected = Arrays.asList(2,3,5,7);
assertEquals("Should return 2,3,5,7", expected, Primes.generatePrimes(2,10));
}
@Test
public void testCase2() {
assertNull("Should return null", Primes.generatePrimes(0, 0));
}
@Test
public void testCase3() {
assertNull("Should return null", Primes.generatePrimes(-4, 4));
}
@Test
public void testCase4() {
List<Integer> expected = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
assertEquals("Should return primes till 100", expected, Primes.generatePrimes(2,100));
}
}
Given a string of open and closed parenthesis output "Balanced" if the parenthesis are balanced or "Unbalanced" otherwise.
A string is balanced if it consists entirely of pairs of opening/closing parenthesis (in that order), none of which mis-nest.
Example input:
(())())
Example output:
Unbalanced
Example input:
(()())
Example output:
Balanced
function balanced_parenthesis(s) {
if(s == null) return null;
var i = 0,
startCnt = 0,
n = s.length;
for(i = 0; i < n; i++) {
if(s[i] === "(") {
startCnt += 1;
} else if(s[i] === ")") {
startCnt -= 1;
if(startCnt < 0) {
break;
}
}
}
if(startCnt !== 0) {
return 'Unbalanced';
} else {
return 'Balanced';
}
}
describe("Balanced Parenthesis Tests", function(){
it ("should return Balanced", function(){
Test.assertEquals(balanced_parenthesis("(()())"), "Balanced");
});
it ("should return Unbalanced", function(){
Test.assertEquals(balanced_parenthesis("(())())"), "Unbalanced");
});
it ("should return Unbalanced", function(){
Test.assertEquals(balanced_parenthesis(")()("), "Unbalanced");
});
it ("should return null for null input", function(){
Test.assertEquals(balanced_parenthesis(), null);
});
});