Skip to content

Commit 881fcf1

Browse files
committed
Day 11 - 16 - Solutions
1 parent bd57550 commit 881fcf1

File tree

9 files changed

+615
-0
lines changed

9 files changed

+615
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.kishan.java.leetcode.juneChallenges;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Random;
6+
7+
public class RandomizedSet {
8+
9+
/**
10+
* Initialize your data structure here.
11+
*/
12+
private Map<Integer, Integer> valueMap;
13+
private Map<Integer, Integer> indexMap;
14+
private Random random = new Random();
15+
16+
public RandomizedSet() {
17+
valueMap = new HashMap<Integer, Integer>();
18+
indexMap = new HashMap<Integer, Integer>();
19+
}
20+
21+
/**
22+
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
23+
*/
24+
public boolean insert(int val) {
25+
if (valueMap.containsKey(val)) {
26+
return false;
27+
}
28+
valueMap.put(val, valueMap.size());
29+
indexMap.put(indexMap.size(), val);
30+
return true;
31+
}
32+
33+
/**
34+
* Removes a value from the set. Returns true if the set contained the specified element.
35+
*/
36+
public boolean remove(int val) {
37+
if (valueMap.containsKey(val)) {
38+
int index = valueMap.get(val);
39+
valueMap.remove(val);
40+
indexMap.remove(index);
41+
Integer tailElem = indexMap.get(indexMap.size());
42+
if (tailElem != null) {
43+
indexMap.put(index, tailElem);
44+
valueMap.put(tailElem, index);
45+
indexMap.remove(indexMap.size()-1);
46+
}
47+
return true;
48+
}
49+
return false;
50+
}
51+
52+
/**
53+
* Get a random element from the set.
54+
*/
55+
public int getRandom() {
56+
if (valueMap.size() == 0) {
57+
return -1;
58+
}
59+
if (valueMap.size() == 1) {
60+
return indexMap.get(0);
61+
}
62+
int index = random.nextInt(valueMap.size());
63+
return indexMap.get(index);
64+
}
65+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package com.kishan.java.leetcode.juneChallenges;
2+
3+
public class Test {
4+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.kishan.scala.leetcode.juneChallenges
2+
3+
import java.util
4+
import java.util.PriorityQueue
5+
6+
import scala.collection.JavaConverters._
7+
8+
object CheapestFlightsWithinKStops {
9+
def main(args: Array[String]): Unit = {
10+
val n = 5 // Number of cities
11+
val edges = Array(Array(1, 2, 10), Array(2, 0, 7), Array(1, 3, 8), Array(4, 0, 10), Array(3, 4, 2), Array(4, 2, 10), Array(0, 3, 3), Array(3, 1, 6), Array(2, 4, 5))
12+
val src = 0
13+
val dst = 4
14+
val k = 1 // Number of Stops
15+
val result = findCheapestPrice(n, edges, src, dst, k)
16+
println(result, result == 5)
17+
18+
}
19+
20+
def findCheapestPrice(n: Int, flights: Array[Array[Int]], src: Int, dst: Int, K: Int): Int = {
21+
22+
if (flights.length == 0) {
23+
return -1
24+
}
25+
//Building Graph
26+
var map: java.util.Map[Int, util.Map[Int, Int]] = new util.HashMap[Int, util.Map[Int, Int]]()
27+
flights.foreach(a => {
28+
if (map.get(a(0)) == null) {
29+
map.put(a(0), new util.HashMap[Int, Int]())
30+
}
31+
map.get(a(0)).put(a(1), a(2))
32+
})
33+
34+
var q: PriorityQueue[Node] = new PriorityQueue[Node]((a, b) => a.cost - b.cost)
35+
q.add(Node(src, 0, -1))
36+
while (!q.isEmpty) {
37+
val curr: Node = q.poll
38+
if (curr.city == dst) return curr.cost
39+
if (curr.stop < K) {
40+
val nexts: util.Map[Int, Int] = map.getOrDefault(curr.city, new util.HashMap[Int, Int])
41+
for (next <- nexts.asScala) {
42+
q.add(Node(next._1, curr.cost + next._2, curr.stop + 1))
43+
}
44+
}
45+
}
46+
return -1
47+
}
48+
}
49+
50+
case class Node(city: Int, cost: Int, stop: Int)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.kishan.scala.leetcode.juneChallenges
2+
3+
4+
/*
5+
* Given a set of distinct positive integers, find the largest subset such that
6+
* every pair (Si, Sj) of elements in this subset satisfies:
7+
* Si % Sj = 0 or Sj % Si = 0.
8+
* If there are multiple solutions, return any subset is fine.
9+
*
10+
* */
11+
12+
/*
13+
* Input: [1,2,3]
14+
Output: [1,2] (of course, [1,3] will also be ok)
15+
* Input: [1,2,4,8]
16+
Output: [1,2,4,8]
17+
* */
18+
19+
/*
20+
* Approach:
21+
*
22+
* We will check if the array is empty or it has only one element. If yes we will return the array as list.
23+
*
24+
* If array length is greater than 1.
25+
* 1. First, we will sort the elements in the array. [3,4,16,8] -> [3,4,8,16]
26+
* 2. We will create a empty Map for which the integer value will be the key and the possible integers will be stored as the list of integers.
27+
* 3. So for every Integer in the list it should need to have the self value in the temp_list of value. Because, the integer will be divisible by itself.
28+
* 4. We will iterate through the each element of the list and if we have any keys in the map we will try to divide the number by the key.
29+
* If the number is divisible and if we have list of integer for the key we will assign this list to temp_list that we created.
30+
* 5. Next, we will add the current number to the temp list and we will put the (key, temp_list) to the map.
31+
* 6. Finally, we will get the values from the map and will return the list with maximum length.
32+
*
33+
* Explanation:
34+
* input = [3,4,16,8]
35+
*
36+
* Step 1: Sorting -> [3,4,8,16]
37+
* Step 2: Create empty Map[Int, List[Int]]
38+
* Step 3: Iterate through the the sorted list
39+
* Step 4: For every int in the list. We will have a key -> value in the Map.
40+
*
41+
* Iteration:
42+
* 3 -> [3]
43+
* 4 % 3 is not equal to 0. temp_list = [] and 4 is divisible by 4. So 4 -> [4]
44+
* 8 % 3 no, 8%4 equal to 0. temp_list = [4] and 8 will be divisible by it self. So 8 -> [4,8]
45+
* 16 % 3 no, 16 % 4. temp_list = [4] and 16 % 8. temp_list = [4,8] and 16 will be divisible by itself. So 16 -> [4,8,16]
46+
*
47+
* we will get values from the map. [[3], [4], [4,8], [4,8,16]] and we will return the list with maximum length.
48+
* */
49+
50+
51+
object LargestDivisibleSubset {
52+
def main(args: Array[String]): Unit = {
53+
val nums = Array(3, 4, 16, 8)
54+
55+
println(largestDivisibleSubset(nums).mkString(","))
56+
}
57+
58+
def largestDivisibleSubset(nums: Array[Int]): List[Int] = {
59+
if (nums.length <= 1) {
60+
return nums.toList
61+
}
62+
val sortedNums = nums.sortBy(a => a)
63+
var map: Map[Int, List[Int]] = Map()
64+
for (num <- sortedNums) {
65+
var list: List[Int] = List()
66+
for (key <- map.keys) {
67+
if (num % key == 0) {
68+
if (map(key).length > list.length) {
69+
list = map(key)
70+
}
71+
}
72+
}
73+
list = list :+ num
74+
map += (num -> list)
75+
}
76+
return map.values.maxBy(_.length)
77+
}
78+
79+
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package com.kishan.scala.leetcode.juneChallenges
2+
3+
import java.util
4+
5+
import scala.util.Random
6+
7+
/*
8+
* Design a data structure that supports all following operations in average O(1) time.
9+
insert(val): Inserts an item val to the set if not already present.
10+
remove(val): Removes an item val from the set if present.
11+
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
12+
* */
13+
14+
/*
15+
*
16+
// Init an empty set.
17+
RandomizedSet randomSet = new RandomizedSet();
18+
19+
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
20+
randomSet.insert(1);
21+
22+
// Returns false as 2 does not exist in the set.
23+
randomSet.remove(2);
24+
25+
// Inserts 2 to the set, returns true. Set now contains [1,2].
26+
randomSet.insert(2);
27+
28+
// getRandom should return either 1 or 2 randomly.
29+
randomSet.getRandom();
30+
31+
// Removes 1 from the set, returns true. Set now contains [2].
32+
randomSet.remove(1);
33+
34+
// 2 was already in the set, so return false.
35+
randomSet.insert(2);
36+
37+
// Since 2 is the only number in the set, getRandom always return 2.
38+
randomSet.getRandom();
39+
* */
40+
41+
/*
42+
* Approach:
43+
*
44+
* 1. Using Map Type we can achieve 0(1) for inserting, accessing and removing item.
45+
* 2. For getting Random number we can create random object using Random and we can get the random integer number which will yield random integer number for the limit. We can use the random integer number to get item from the Map.
46+
*
47+
* First, we will create two map object -
48+
* a. valueMap object will hold the value as key and index as value.
49+
* b. indexMap object will hold the index as key and value as value.
50+
*
51+
* Insert Operation:
52+
* When ever we want a value to be inserted into the valueMap. First we will check if valueMap contains that value. If it doesn't have the value we will insert the element into valueMap with the index as value and we will insert value to the indexMap with index as key.
53+
*
54+
* Remove Operation:
55+
* 1. First, we will get the index of the value to be removed from the valueMap.
56+
* 2. We will remove the index from the valueMap and value from indexMap.
57+
* 3. Now we have to replace the index value that has been removed, with the last Index i.e If [0,1,2] are our Indices and we removed 1 so we will have [0,2]. Now, we have to replace 2 with 1. By doing so we will not have any discrepancy in the order of index values.
58+
* 4. For that we will get the tail element from the indexMap.
59+
* 5. We will replace the index of the tail element with the index of the value that we removed and we will create new entry for that index in the indexMap and we will remove the tailelem from the indexMap
60+
*
61+
* getRandom:
62+
* 1. If the size of value map is 0 we will return -1. If size of value map is 1 we will return tail or head of values from the indexMap.
63+
* 2. For other cases we have to get the random integer value for the length of valueMap.
64+
* 3. We will use the randomInteger value to get the item from the indexMap.
65+
* */
66+
67+
68+
class RandomizedSet() {
69+
70+
private val random = new Random()
71+
/** Initialize your data structure here. */
72+
private var valueMap: java.util.Map[Int, Int] = new util.HashMap[Int, Int]()
73+
private var indexMap: java.util.Map[Int, Int] = new util.HashMap[Int, Int]()
74+
75+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
76+
def insert(`val`: Int): Boolean = {
77+
if (valueMap.getOrDefault(`val`, Int.MinValue) != Int.MinValue) {
78+
false
79+
} else {
80+
valueMap.put(`val`, valueMap.size())
81+
indexMap.put(indexMap.size(), `val`)
82+
true
83+
}
84+
}
85+
86+
/** Removes a value from the set. Returns true if the set contained the specified element. */
87+
def remove(`val`: Int): Boolean = {
88+
if (valueMap.getOrDefault(`val`, Int.MinValue) != Int.MinValue) {
89+
val index = valueMap.get(`val`)
90+
valueMap.remove(`val`)
91+
indexMap.remove(index)
92+
val tailElem = indexMap.getOrDefault(indexMap.size, Int.MinValue)
93+
if (tailElem != Int.MinValue) {
94+
indexMap.put(index, tailElem)
95+
valueMap.put(tailElem, index)
96+
indexMap.remove(indexMap.size()-1)
97+
}
98+
true
99+
} else {
100+
false
101+
}
102+
}
103+
104+
/** Get a random element from the set. */
105+
def getRandom(): Int = {
106+
if (valueMap.size == 0) {
107+
return -1
108+
}
109+
110+
if (valueMap.size == 1) {
111+
return indexMap.get(0)
112+
}
113+
val index: Int = random.nextInt(valueMap.size)
114+
115+
indexMap.get(index)
116+
}
117+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.kishan.scala.leetcode.juneChallenges
2+
3+
import scala.annotation.tailrec
4+
5+
/*
6+
* Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value.
7+
* Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
8+
*
9+
* */
10+
11+
/*
12+
* Given the tree:
13+
4
14+
/ \
15+
2 7
16+
/ \
17+
1 3
18+
19+
And the value to search: 2
20+
*
21+
* Output:
22+
* 2
23+
/ \
24+
1 3
25+
*
26+
* In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.
27+
Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
28+
* */
29+
30+
31+
/*
32+
* Approach: Tail Recursion
33+
* 1. We will check the root.value == val. If equal we will return the root.
34+
* 2. If val < root.value and root.left is not null then our val should be in the left side of the root. Now we will call the function recursively.
35+
* 3. Similarly if val > root.value and root.right is not null we will call the function recursively and our val will be in the right side of the tree.
36+
* 4. Finally, If our val is not found we are creating a value of Type TreeNode and assigning null value to it. We will return the Empty TreeNode.
37+
*
38+
* */
39+
40+
object SearchInBST {
41+
@tailrec
42+
def searchBST(root: TreeNode, `val`: Int): TreeNode = {
43+
if (root.value == `val`) {
44+
root
45+
} else if (`val` < root.value && root.left != null) {
46+
searchBST(root.left, `val`)
47+
} else if (`val` > root.value && root.right != null) {
48+
searchBST(root.right, `val`)
49+
} else {
50+
val t: TreeNode = null
51+
t
52+
}
53+
}
54+
55+
def main(args: Array[String]): Unit = {
56+
val t: TreeNode = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)), new TreeNode(7))
57+
println("Input Binary Tree: " + t)
58+
println("Result Binary Tree: " + searchBST(t, 7))
59+
}
60+
}

0 commit comments

Comments
 (0)