The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:

A chess knight can move as indicated in the chess diagram below:

We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).

Given an integer n, return how many distinct phone numbers of length n we can dial.

You are allowed to place the knight on any numeric cell initially and then you should perform n – 1 jumps to dial a number of length n. All jumps should be valid knight jumps.

As the answer may be very large, return the answer modulo 109 + 7.

**Input:** n = 1**Output:** 10**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.

**Input**: n = 2**Output**: 20**Explanation**: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]

**Input**: n = 3131**Output**: 136006598**Explanation**: Please take care of the mod.

- 1 <= n <= 5000

class Solution { private static final int MOD = 1_000_000_007; public int knightDialer(int n) { List[] map = new List[10]; map[0] = List.of(4, 6); map[1] = List.of(6, 8); map[2] = List.of(7, 9); map[3] = List.of(4, 8); map[4] = List.of(0, 3, 9); map[5] = Collections.EMPTY_LIST; map[6] = List.of(0, 1, 7); map[7] = List.of(2, 6); map[8] = List.of(1, 3); map[9] = List.of(2, 4); //dp(i, j) denotes the no of ways to reach i in j steps int[][] dp = new int[10][n+1]; //no. of ways to reach i in 1 step for(int i=0;i<10;i++){ dp[i][1] = 1; } //j steps for(int j=2;j<=n;j++){ for(int i=0;i<10;i++){ dp[i][j] = 0; for(Object k: map[i]){ dp[i][j] = (dp[i][j]+dp[(Integer)k][j-1])%MOD; } } } int sum = 0; for(int i=0;i<10;i++){ sum = (sum + dp[i][n])%MOD; } return sum; } }]]>

Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.

**Input:** nums = [“01″,”10”]**Output:** “11”**Explanation:** “11” does not appear in nums. “00” would also be correct.

**Input:** nums = [“00″,”01”]**Output:** “11”**Explanation:** “11” does not appear in nums. “10” would also be correct.

**Input:** nums = [“111″,”011″,”001”]**Output:** “101”**Explanation:** “101” does not appear in nums. “000”, “010”, “100”, and “110” would also be correct.

- n == nums.length
- 1 <= n <= 16
- nums[i].length == n
- nums[i] is either ‘0’ or ‘1’.
- All the strings of nums are unique.

class Solution { public String findDifferentBinaryString(String[] nums) { Set<String> set = new HashSet<>(); for(String s: nums){ set.add(s); } return dfs(nums.length, set, ""); } private String dfs(int n, Set<String> exist, String s){ if(n == 0){ //check if the string exists if(!exist.contains(s)) return s; return null; } int[] x= {0, 1}; for(int i=0;i<x.length;i++){ String a; //append x[i] to the string if((a = dfs(n-1, exist, s+x[i]))!=null){ return a; } //otherwise backtrack } return null; } }]]>

You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.

The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.

Return the minimum unfairness of all distributions.

**Input**: cookies = [8,15,10,20,8], k = 2**Output**: 31**Explanation**: One optimal distribution is [8,15,8] and [10,20]

- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.

The unfairness of the distribution is max(31,30) = 31.

It can be shown that there is no distribution with an unfairness less than 31.

**Input**: cookies = [6,1,3,2,2,4,1,2], k = 3**Output**: 7**Explanation**: One optimal distribution is [6,1], [3,2,2], and [4,1,2]

- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.

The unfairness of the distribution is max(7,7,7) = 7.

It can be shown that there is no distribution with an unfairness less than 7.

- 2 <= cookies.length <= 8
- 1 <= cookies[i] <= 105
- 2 <= k <= cookies.length

class Solution { public int distributeCookies(int[] cookies, int k) { int[] arr = new int[k]; dfs(cookies, arr, 0); return min; } private void dfs(int[] cookies, int[] arr, int idxC){ if(idxC>=cookies.length){ max(arr); return; } for(int i=0;i<arr.length;i++){ //give idxC bag of cookie to the ith child arr[i]+=cookies[idxC]; dfs(cookies, arr, idxC+1); //backtrack arr[i]-=cookies[idxC]; } } int min = Integer.MAX_VALUE; private void max(int[] arr){ int max = 0; for(int a: arr){ max = Math.max(max, a); } min = Math.min(max, min); return; } }]]>

You are given two integers height and width representing a garden of size height x width. You are also given:

- an array tree where tree = [treer, treec] is the position of the tree in the garden,
- an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel in the garden,
- and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden.

The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.

Return the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one.

The distance is the number of moves.

**Input:** height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]**Output:** 12**Explanation:** The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.

**Input:** height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]**Output:** 3

- 1 <= height, width <= 100
- tree.length == 2
- squirrel.length == 2
- 1 <= nuts.length <= 5000
- nuts[i].length == 2
- 0 <= treer, squirrelr, nutir <= height
- 0 <= treec, squirrelc, nutic <= width

class Solution { public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { int[] treeDist = new int[nuts.length]; int[] totalDist = new int[nuts.length]; int sx = squirrel[0]; int sy = squirrel[1]; int tx = tree[0]; int ty = tree[1]; int sum = 0; for(int i=0;i<nuts.length;i++){ treeDist[i] = distance(tx, ty, nuts[i][0], nuts[i][1]); totalDist[i] = distance(sx, sy, nuts[i][0], nuts[i][1]) + treeDist[i]; sum += treeDist[i]*2; } int minDist = Integer.MAX_VALUE; for(int i=0;i<treeDist.length;i++){ int dist = sum - 2 * treeDist[i] + totalDist[i]; if(dist < minDist){ minDist = dist; } } return minDist; } private int distance(int x1, int y1, int x2, int y2){ return Math.abs(x1-x2) + Math.abs(y1-y2); } }]]>

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

**Input**: arr = [3,5,1]**Output**: true**Explanation**: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.

**Input:** arr = [1,2,4]**Output:** false**Explanation:** There is no way to reorder the elements to obtain an arithmetic progression.

- 2 <= arr.length <= 1000
- -106 <= arr[i] <= 106

class Solution { public boolean canMakeArithmeticProgression(int[] arr) { if(arr==null || arr.length<2) return false; Arrays.sort(arr); int diff = arr[1] - arr[0]; for(int i=2;i<arr.length;i++) { if(arr[i] - arr[i-1]!=diff) return false; } return true; } }]]>

On a campus represented on the X-Y plane, there are n workers and m bikes, with n <= m.

You are given an array workers of length n where workers[i] = [xi, yi] is the position of the ith worker. You are also given an array bikes of length m where bikes[j] = [xj, yj] is the position of the jth bike. All the given positions are unique.

Assign a bike to each worker. Among the available bikes and workers, we choose the (workeri, bikej) pair with the shortest Manhattan distance between each other and assign the bike to that worker.

If there are multiple (workeri, bikej) pairs with the same shortest Manhattan distance, we choose the pair with the smallest worker index. If there are multiple ways to do that, we choose the pair with the smallest bike index. Repeat this process until there are no available workers.

Return an array answer of length n, where answer[i] is the index (0-indexed) of the bike the ith worker is assigned to.

The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x – p2.x| + |p1.y – p2.y|.

**Input:** workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]**Output:** [1,0]**Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].

**Input:** workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]**Output:** [0,2,1]**Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is [0,2,1].

- n == workers.length
- m == bikes.length
- 1 <= n <= m <= 1000
- workers[i].length == bikes[j].length == 2
- 0 <= xi, yi < 1000
- 0 <= xj, yj < 1000
- All worker and bike locations are unique.

class Solution { TLE public int[] assignBikes(int[][] workers, int[][] bikes) { Map<String, Integer> bikeMap = new HashMap<>(); for(int i=0;i<bikes.length;i++){ bikeMap.put(bikes[i][0]+":"+bikes[i][1], i); } Queue<Worker> next = new LinkedList<>(); HashSet<Integer> assigned = new HashSet<>(); HashSet<String> visited = new HashSet<>(); for(int i=0; i<workers.length; i++){ next.offer(new Worker(workers[i][0], workers[i][1], i)); visited.add(workers[i][0] + ":" + workers[i][1] + ":" + i); } int[] assignments = new int[workers.length]; int[] x = {-1, 0, 0, 1}; int[] y = {0, -1, 1, 0}; while(!next.isEmpty()){ int len = next.size(); for(int i=0;i<len;i++){ Worker w = next.poll(); if(assigned.contains(w.index)){ continue; } String key = w.x+":"+w.y; if(bikeMap.containsKey(key)){ assignments[w.index] = bikeMap.remove(key); assigned.add(w.index); } if(assigned.size()==workers.length){ return assignments; } for(int j=0;j<x.length;j++){ int px = x[j] + w.x; int py = y[j] + w.y; if(isValid(px, py, w.index, visited)){ next.offer(new Worker(px, py, w.index)); visited.add(px + ":"+ py + ":"+ w.index); } } } } return null; } private boolean isValid(int px, int py, int pi, HashSet<String> visited){ return px >=0 && px < 1000 && py >= 0 && py < 1000 && !visited.contains(px + ":" + py + ":" + pi); } static class Worker { int x; int y; int index; public Worker(int x, int y, int index){ this.x = x; this.y = y; this.index = index; } } }

class Solution { public int[] assignBikes(int[][] workers, int[][] bikes) { Map<Integer, PriorityQueue<Bike>> map = initialize(workers, bikes); HashSet<Integer> workerAssigned = new HashSet<>(); HashSet<Integer> bikeAssigned = new HashSet<>(); int[] assigned = new int[workers.length]; for(int i=0;i<workers.length;i++){ int minDist = Integer.MAX_VALUE; int minIndex = 1000; int bike = -1; for(Map.Entry<Integer, PriorityQueue<Bike>> entry: map.entrySet()){ int wi = entry.getKey(); PriorityQueue<Bike> p = entry.getValue(); while(!p.isEmpty() && bikeAssigned.contains(p.peek().index)){ p.poll(); } if(!p.isEmpty()){ Bike b = p.peek(); if(b.dist < minDist || (b.dist==minDist && wi < minIndex)){ minDist = b.dist; minIndex = wi; bike = b.index; } } } map.remove(minIndex); assigned[minIndex] = bike; workerAssigned.add(minIndex); bikeAssigned.add(bike); if(workerAssigned.size()==workers.length){ return assigned; } } return null; } private Map<Integer, PriorityQueue<Bike>> initialize(int[][] workers, int[][] bikes){ Map<Integer, PriorityQueue<Bike>> map = new HashMap<>(); for(int i=0; i<workers.length;i++){ int wx = workers[i][0]; int wy = workers[i][1]; PriorityQueue<Bike> p = new PriorityQueue<>(new Comparator<Bike>(){ public int compare(Bike a, Bike b){ int res = a.dist - b.dist; if(res==0){ res = a.index - b.index; } return res; } }); for(int j=0;j<bikes.length;j++){ int bx = bikes[j][0]; int by = bikes[j][1]; p.offer(new Bike(wx, wy, bx, by, j)); } map.put(i, p); } return map; } static class Bike { int x; int y; int index; int dist; public Bike (int wx, int wy, int x, int y, int index){ this.x = x; this.y = y; this.index = index; this.dist = distance(wx, wy, x, y); } } private static int distance(int wx, int wy, int bx, int by){ return Math.abs(wx- bx) + Math.abs(wy-by); } }]]>

You have planned some train traveling one year in advance. The days of the year you will travel are given as an integer array days. Each day is an integer from 1 to 365.

Train tickets are sold in three different ways:

- a 1-day pass is sold for costs[0] dollars,
- a 7-day pass is sold for costs[1] dollars, and
- a 30-day pass is sold for costs[2] dollars.

The passes allow that many days of consecutive travel.

For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.

Return the minimum number of dollars you need to travel every day in the given list of days.

**Input:** days = [1,4,6,7,8,20], costs = [2,7,15]**Output:** 11**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:

On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.

On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, …, 9.

On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.

In total, you spent $11 and covered all the days of your travel.

**Input:** days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]**Output:** 17**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:

On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, …, 30.

On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.

In total, you spent $17 and covered all the days of your travel.

- 1 <= days.length <= 365
- 1 <= days[i] <= 365
- days is in strictly increasing order.
- costs.length == 3
- 1 <= costs[i] <= 1000

class Solution { public int mincostTickets(int[] days, int[] costs) { int[][] memo = new int[days.length+1][720]; for(int[] m: memo){ Arrays.fill(m, -1); } return dfs(days, costs, 0, 0, memo); } private int dfs(int[] days, int[] costs, int remainingDays, int index, int[][] memo){ if(index >= days.length){ return 0; } if(memo[index][remainingDays]!=-1){ return memo[index][remainingDays]; } int min = Integer.MAX_VALUE; if(remainingDays >= days[index]){ min = Math.min(min, dfs(days, costs, remainingDays, index+1, memo)); } else { for(int i=0;i<costs.length;i++){ min = Math.min(min, costs[i] + dfs(days, costs, days[index]+getDays(i), index+1, memo)); } } memo[index][remainingDays] = min; return min; } private int getDays(int index){ switch(index){ case 0: return 0; case 1: return 6; case 2: return 29; } return -1; } }]]>

a. Create an EC2 instance with the following config

- Name: MyEC2Server
- AMI: Amazon Linux 2023 AMI

b. Create a Key Pair (pem extension), with name MyKeyPair

c. Create a Security Group named ‘MyEC2Server_SG’, to allow SSH and HTTP Traffic from anywhere.

d. Add the following script to the User data Section. This is to install Apache Server and create an index.html file under /var/www/html folder with “Hello World”

#!/bin/bash sudo su yum update -y yum install httpd -y echo "<html><h1> Hello World </h1><html>" >> /var/www/html/index.html systemctl start httpd systemctl enable httpd

e. Launch Instance

**Note:** If the Public IP of the instance is not opening any page, Make sure the URL Protocol is **HTTP, **not **HTTPS**. Please wait until the status check of the instance is transitioned from initializing to 2/2 checks passed. This may take up to 5 minutes. If the page still does not load, make sure to check the Security group’s inbound rule and see if the entry for HTTP exists or not.

e. Once the instance is in a Running state and all the status checks passed. Try accessing the index.html by the following URL in the browser.

HTTP://<public_ip_address>

a. From the Actions dropdown, select Image and Templates > Create Image

b.

Image Name: MyEC2Image

Image Description: My EC2 Image

and Click on Create Image

c. From the left-hand-side panel, select AMIs.

Wait for the status to be changed from Pending to Available

Status > Available

d. Once the status changed to Available, click on Launch Instances from AMI

Name: MyEC2AMIServer

Select the keypair you previously created.

Select the security group you have previously created

e. Once the new instance is in a Running state and all the status checks have passed, try accessing the page by going to the public address.

]]>There are n computers numbered from 0 to n – 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.

You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.

Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.

**Input:** n = 4, connections = [[0,1],[0,2],[1,2]]**Output:** 1**Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3.

**Input:** n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]**Output:** 2

**Input:** n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]**Output:** -1**Explanation:** There are not enough cables.

- 1 <= n <= 105
- 1 <= connections.length <= min(n * (n – 1) / 2, 105)
- connections[i].length == 2
- 0 <= ai, bi < n
- ai != bi
- There are no repeated connections.
- No two computers are connected by more than one cable.

class Solution { public int makeConnected(int n, int[][] connections) { // int totalConnections = n-1; if(connections.length < totalConnections) return -1; int[] parent = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; } for(int[] connection: connections){ int min = Math.min(connection[0], connection[1]); int max = Math.max(connection[0], connection[1]); union(parent, max, min); } HashSet<Integer> set = new HashSet<>(); for(int i=0;i<parent.length;i++){ set.add(find(parent, parent[i])); } return set.size()-1; } private int find(int[] parent, int x){ int n = x; while(n!=parent[n]){ n = parent[n]; } parent[x] = n; return n; } private void union(int[] parent, int x, int y){ int parentX = find(parent, x); int parentY = find(parent, y); if(parent[parentX]!=parent[parentY]){ parent[parentX] = parentY; } } }]]>