Skip to content

Commit 49af2bd

Browse files
author
anitaa
committed
First commit - Added a few algorithms for interview practice
0 parents  commit 49af2bd

25 files changed

+2101
-0
lines changed

src/AlgoTest.java

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import java.util.*;
2+
3+
public class AlgoTest {
4+
5+
public static void main(String[] args) {
6+
// int[] arr = {-2, -3, -3, -1, -2, -1, -5, -3};
7+
8+
// //answer should be: 7
9+
// System.out.println(findMaxSubArray(arr.length, arr));
10+
//
11+
// System.out.println(isBalanced("{()}[]"));
12+
13+
// int[] arr2 = {1,2,3,4,5};
14+
// findMinMaxSum(arr2);
15+
16+
// int[] arr3 = {4, 73, 67, 38, 33};
17+
// System.out.println(Arrays.toString(gradingStudents(arr3)));
18+
19+
// System.out.println(calculateLCM(3, 2));
20+
// System.out.println(kangaroo(21, 6, 47, 3));
21+
22+
// String s = "haveaniceday";
23+
// double value = Math.sqrt(s.length());
24+
25+
}
26+
27+
28+
29+
30+
31+
32+
/* Kandane's Algorithm */
33+
public static int findMaxSubArray(int length, int[] arr) {
34+
35+
int max_so_far = 0;
36+
int max_at_end = 0;
37+
38+
for(int i=0; i<length; i++) {
39+
max_at_end = Math.max(0, max_at_end + arr[i]);
40+
max_so_far = Math.max(max_so_far, max_at_end);
41+
}
42+
return max_so_far;
43+
}
44+
45+
46+
/* Check if an expression is balanced */
47+
public static boolean isBalanced(String s) {
48+
Stack<Character> stack = new Stack();
49+
50+
for(char c: s.toCharArray()) {
51+
if(c == '[' || c =='{' || c == '(') {
52+
stack.push(c);
53+
54+
} else if(c == ']' && (stack.isEmpty() || stack.pop() != '[')) {
55+
return false;
56+
57+
} else if(c == '}' && (stack.isEmpty() || stack.pop() != '{')) {
58+
return false;
59+
60+
} else if(c == ')' && (stack.isEmpty() || stack.pop() != '(')) {
61+
return false;
62+
}
63+
}
64+
return true;
65+
}
66+
67+
68+
public static void findMinMaxSum(int[] arr) {
69+
long sum = 0;
70+
long maxSum = 0;
71+
long minSum = Long.MAX_VALUE;
72+
73+
for(int i=0; i<arr.length; i++) {
74+
if(arr[i] < minSum) {
75+
minSum = arr[i];
76+
}
77+
if(arr[i] > maxSum) {
78+
maxSum = arr[i];
79+
}
80+
sum+= arr[i];
81+
}
82+
System.out.print((sum - maxSum) + " " + (sum - minSum));
83+
}
84+
85+
86+
//https://www.hackerrank.com/challenges/birthday-cake-candles
87+
static int birthdayCakeCandles(int n, int[] arr) {
88+
int max = Integer.MIN_VALUE;
89+
int count = 0;
90+
for(int i=0; i<n; i++) {
91+
if(max < arr[i]) {
92+
max = arr[i];
93+
count = 1;
94+
}
95+
else if(max == arr[i]) {
96+
count++;
97+
}
98+
}
99+
return count;
100+
}
101+
102+
/* https://www.hackerrank.com/challenges/grading/problem */
103+
static int[] gradingStudents(int[] grades) {
104+
List<Integer> arr = new ArrayList();
105+
for(int grade: grades) {
106+
int nextHighestMultiple = (5 *(grade/5))+5;
107+
int diff = nextHighestMultiple - grade;
108+
int newValue = (diff >= 3) || (grade < 38) ? grade : nextHighestMultiple;
109+
arr.add(newValue);
110+
}
111+
return toIntArray(arr);
112+
}
113+
114+
115+
116+
117+
private static int[] toIntArray(List<Integer> list) {
118+
int[] ret = new int[list.size()];
119+
int i = 0;
120+
for (Integer e : list) {
121+
ret[i++] = e.intValue();
122+
}
123+
return ret;
124+
}
125+
126+
127+
128+
/* https://www.hackerrank.com/challenges/apple-and-orange/problem */
129+
private static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
130+
int appleCount=0, orangeCount = 0;
131+
for(int apple: apples) {
132+
int distance = a + apple;
133+
if(distance >= s && distance <= t) {
134+
appleCount++;
135+
}
136+
}
137+
138+
for(int orange: oranges) {
139+
int distance = b + orange;
140+
if(distance >= s && distance <= t) {
141+
orangeCount++;
142+
}
143+
}
144+
System.out.println(appleCount + "\n" + orangeCount);
145+
}
146+
147+
148+
private static int calculateGCM(int a, int b) {
149+
int max = Math.max(a,b);
150+
int min = Math.min(a,b);
151+
while((max-min) != 0) {
152+
int diff = max-min;
153+
if(diff < min) {
154+
min = diff;
155+
} else {
156+
max = diff;
157+
}
158+
}
159+
return max;
160+
}
161+
162+
private static int calculateLCM(int a, int b) {
163+
//lcm(a, b) = a × b / gcd(a, b).
164+
int gcm = calculateGCM(a,b);
165+
int lcm = (a*b)/gcm;
166+
return lcm;
167+
}
168+
169+
/* https://www.hackerrank.com/challenges/kangaroo/problem */
170+
static String kangaroo(int x1, int v1, int x2, int v2) {
171+
String result = "YES";
172+
double possibleMeetingValue = (double) (x2-x1)/(v1-v2);
173+
if( possibleMeetingValue<=0 || (possibleMeetingValue % 1 != 0 ) )
174+
result = "NO";
175+
176+
return result;
177+
}
178+
}

src/arrays/FindMaximumSellProfit.java

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package arrays;
2+
3+
4+
import com.sun.tools.javac.util.Pair;
5+
6+
public class FindMaximumSellProfit {
7+
8+
/*
9+
* Given an array representing prices of the stock on different days,
10+
* find the maximum profit that can be earned by performing maximum of one transaction.
11+
* A transaction consists of activity of buying and selling the stock on different or same days.
12+
*
13+
* Eg: 1 - {100, 80, 120, 130, 70, 60, 100, 125}
14+
* the price of the stock on day-1 is 100, on day-2 is 80 and so on.
15+
* The maximum profit that could be earned in this window is 65 (buy at 60 and sell at 125).
16+
*
17+
* Eg: 2 - For price array - {100, 80, 70, 65, 60, 55, 50}, maximum profit that could be earned is 0.
18+
*
19+
* */
20+
21+
22+
public static int findMaximumProfit(int[] stockPrices) {
23+
int minimumPrice = Integer.MAX_VALUE;
24+
int maxProfit = 0;
25+
26+
/*
27+
* The profit is the maximum value of the maximumProfit so far and
28+
* the difference between the current element(selling price) and the minimum buying price - i.e. profit for that buy
29+
* Profit = current selling price - the minimum buying price
30+
*
31+
* Minimum buying price is the minimum value between the current element and the minimum price
32+
* */
33+
for(int i=0; i<stockPrices.length; i++) {
34+
maxProfit = Math.max(maxProfit, stockPrices[i]-minimumPrice);
35+
minimumPrice = Math.min(minimumPrice, stockPrices[i]);
36+
}
37+
38+
return maxProfit;
39+
}
40+
41+
42+
43+
44+
45+
46+
47+
48+
49+
50+
51+
52+
53+
54+
55+
56+
57+
58+
59+
public static Pair<Integer, Integer> findMaximumSellProfit(int length, int[] arr) {
60+
int currentBuy = arr[0];
61+
int globalSell = arr[1];
62+
int globalProfit = globalSell - currentBuy;
63+
64+
int currentProfit;
65+
66+
for(int i=1; i< length; i++) {
67+
int currentSell = arr[i];
68+
currentProfit = currentSell - currentBuy;
69+
70+
if(currentProfit > globalProfit) {
71+
globalProfit = currentProfit;
72+
globalSell = arr[i];
73+
}
74+
75+
if(currentBuy > arr[i]) {
76+
currentBuy = arr[i];
77+
}
78+
}
79+
80+
int optimalBuyPrice = globalSell-globalProfit;
81+
int optimalSellPrice = globalSell;
82+
return Pair.of(optimalBuyPrice, optimalSellPrice) ;
83+
}
84+
85+
86+
87+
88+
89+
public static void main(String[] args) {
90+
int[] arr = {100, 80, 120, 130, 70, 60, 100, 125};
91+
System.out.println(findMaximumSellProfit(arr.length, arr));
92+
System.out.println(findMaximumProfit(arr));
93+
}
94+
}

src/arrays/LowHighIndex.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package arrays;
2+
3+
public class LowHighIndex {
4+
5+
6+
/*
7+
* Given a sorted array of integers, return the low and high index of the given key.
8+
* Return -1 if not found. The array length can be in millions with lots of duplicates.
9+
* */
10+
11+
12+
/*
13+
* Linear search might be inefficient if the arr length exceeds a millions elements
14+
* so we can use a modified version of binary search
15+
* */
16+
17+
/*
18+
* Since we are using binary search the runtime complexity is Logarithmic, O(logn).
19+
* Memory Complexity = O(1)
20+
* */
21+
public static void findLowestHighestIndex(int[] arr, int key) {
22+
int lowestIndex = arr.length-1;
23+
int highestIndex = 0;
24+
25+
for(int i=0; i<arr.length; i++) {
26+
if(arr[i] == key) {
27+
if(i < lowestIndex) {
28+
lowestIndex = i;
29+
30+
}
31+
if(i > highestIndex) {
32+
highestIndex = i;
33+
}
34+
}
35+
}
36+
System.out.println(lowestIndex + " " + highestIndex);
37+
}
38+
39+
40+
41+
42+
public static void main(String[] args) {
43+
int[] arr = {1, 2, 5, 5, 5, 5, 5, 5, 5, 5, 20};
44+
findLowestHighestIndex(arr, 5);
45+
}
46+
47+
}

0 commit comments

Comments
 (0)