Minimum Steps to Traverse Points in an Infinite 2D Grid Problem

Problem You are in an infinite 2D grid where you can move in any of the 8 directions: (x,y) to (x+1, y), (x - 1, y), (x, y+1), (x, y-1), (x-1, y-1), (x+1,y+1), (x-1,y+1), (x+1,y-1) ...

Conditional selection between x and y with bitwise operations problem

Problem Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, using only mathematical or bit operations. You can assume b can only be 1 or 0. Solution Method 1 - Using bitwise masks The core idea is to leverage bitwise operations to create masks based on the value of b, which will then be used to select either x or y. ...

Alternating Two-Instance Singleton Pattern Problem

Problem Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances. And in every even call of getInstance(), return the first instance and in every odd call of getInstance(), return the second instance. Solution Method 1 - Using Singleton Pattern Here is the explanation: instances: An array holding the two singleton instances. callCount: A counter to keep track of how many times getInstance is called. Private Constructor: Ensures that the class cannot be instantiated directly. synchronized getInstance: Synchronisation is used to make the method thread-safe. It ensures that only one thread can execute this method at a time, avoiding the creation of multiple instances in a multi-threaded environment. Modulo Operator (%): Used to alternate between the two singleton instances based on the call count. Lazy Initialization: The instances are created only when they are first needed. Code Java public class TwoInstanceSingleton { private static final TwoInstanceSingleton[] instances = new TwoInstanceSingleton[2]; private static int callCount = 0; // Private constructor to prevent instantiation private TwoInstanceSingleton() {} public static synchronized TwoInstanceSingleton getInstance() { int index = callCount % 2; // Lazily initialize the instance if (instances[index] == null) { instances[index] = new TwoInstanceSingleton(); } callCount++; return instances[index]; } // Example usage public static void main(String[] args) { TwoInstanceSingleton obj1 = TwoInstanceSingleton.getInstance(); TwoInstanceSingleton obj2 = TwoInstanceSingleton.getInstance(); TwoInstanceSingleton obj3 = TwoInstanceSingleton.getInstance(); TwoInstanceSingleton obj4 = TwoInstanceSingleton.getInstance(); System.out.println(obj1 == obj2); // false System.out.println(obj1 == obj3); // true System.out.println(obj2 == obj4); // true System.out.println(obj1 == obj4); // false } } ...

Validating Consistency of Directional Rules Between Points Problem

Problem A rule looks like this: A NE B This means this means point A is located northeast of point B. A SW C means that point A is southwest of C. Given a list of rules, check if the sum of the rules validate. Examples Example 1: Input: rules = [ "A N B", "B NE C", "C N A" ] Output: false Explanation: does not validate, since `A` cannot be both north and south of `C`. ...

Capturing Loop Variables in Lambdas Problem

Problem What does the below code snippet print out? How can we fix the anonymous functions to behave as we’d expect? functions = [] for i in range(10): functions.append(lambda : i) for f in functions: print(f()) Solution Method 1 - Using default argument at creation The given code snippet will print the number 9 ten times. This happens because the anonymous functions (lambdas) capture the variable i by reference. When the functions are eventually called in the print loop, they all refer to the final value that i held in the for loop, which is 9. ...

Read N characters given read7

Problem Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters. For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”. Solution Method 1 - Using Iteration Here are the steps: Buffer Management: Maintain a buffer to store characters read by read7() that weren’t consumed by readN(n) calls. Reading n Characters: Continuously read using read7() until we have at least n characters in total. If read7() returns fewer than 7 characters, we’ve likely reached the end of the file. Serve the Required Characters: Serve characters from the buffer to fulfill the readN(n) request. Code Java public class FileReader { private String content; private int index; public FileReader(String content) { this.content = content; this.index = 0; } public String read7() { if (index >= content.length()) { return ""; } int end = Math.min(index + 7, content.length()); String result = content.substring(index, end); index += 7; return result; } } public class Solution { private FileReader fileReader; private Queue<Character> buffer; public Solution(FileReader fileReader) { this.fileReader = fileReader; this.buffer = new LinkedList<>(); } public String readN(int n) { StringBuilder result = new StringBuilder(); while (result.length() < n) { // If buffer is empty, read more characters using read7() if (buffer.isEmpty()) { String readData = fileReader.read7(); if (readData.isEmpty()) { break; } for (char c : readData.toCharArray()) { buffer.offer(c); } } // Add buffered characters to the result while (!buffer.isEmpty() && result.length() < n) { result.append(buffer.poll()); } } return result.toString(); } } ...

Minimum Columns to Remove for Lexicographical Order in Matrix Problem

Problem You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is lexicographically later as you go down each row. It does not matter whether each row itself is ordered lexicographically. For example, given the following table: ...

Efficient Conversion Between Imperial Distance Units Problem

Problem The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure distance. There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on. Create a data structure that can efficiently convert a certain quantity of one unit to the correct amount of any other unit. You should also allow for additional units to be added to the system. ...

Determining the Existence of a Valid Secret Code in Mastermind Based on Given Guesses and Scores

Problem Mastermind is a two-player game in which the first player attempts to guess the secret code of the second. In this version, the code may be any six-digit number with all distinct digits. Each turn the first player guesses some number, and the second player responds by saying how many digits in this number correctly matched their location in the secret code. For example, if the secret code were 123456, then a guess of 175286 would score two, since 1 and 6 were correctly placed. ...

Minimum Steps to reduce number to 1

Problem Given a positive integer N, find the smallest number of steps it will take to reach 1. There are two kinds of permitted steps: You may decrement N to N - 1. If a * b = N, you may decrement N to the larger of a and b. Examples Example 1: Input: N = 100 Output: 5 Explanation: 100 -> 1 with the following route: `100 -> 10 -> 9 -> 3 -> 2 -> 1`. ...

This site uses cookies to improve your experience on our website. By using and continuing to navigate this website, you accept this. Privacy Policy