Posts

Showing posts with the label hashset

String Trimmer

String Trimmer – A Fundamental Filtering Problem Problem Statement You are given T test cases. Each test case consists of two strings, A and B , comprised of lowercase English letters and separated by a space. Your task is to remove from string A all characters that are present in string B . The resulting string should preserve the original order of characters in A , excluding any characters that occur in B . Examples Input 2 data structures smart interviews Output srucures ineview Explanation In the first case, we remove all characters from "data structures" that appear in "smart" , resulting in "srucures" . In the second case, we remove characters from "interviews" that appear in "smart" , resulting in "ineview" . Best Data Structure for the Job To determine membership of a character in B efficiently, a HashSet is ideal. It provides constant-time average lookup and allows us to quickly veri...

Destination City

Destination City – A Simple Graph Traversal Insight Problem Statement You are given a list of paths , where each paths[i] = [cityAi, cityBi] represents a direct path from city Ai to city Bi . The cities form a straight-line route with no cycles or branches. Your task is to find the destination city —the one with no outgoing path . It is guaranteed that the graph forms a valid line and has exactly one such city. Examples Input: [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]] Output: "Sao Paulo" Best Data Structure for the Job A HashSet is ideal for efficiently storing all source cities. Any city that appears only as a destination and never as a source is the final destination. Different Approaches Approach 1: Brute Force  This method checks for each destination city if it never appears as a source . It does this using nested loops. import java.util.*; public class Destinat...

Rearrange Sequence Problem

Rearrange Sequence Problem – Largest Subarray that Can Be Rearranged to Form a Contiguous Sequence Problem Statement: You are given an array of size N containing integers which may not be unique. Your task is to find the size of the largest subarray that can be rearranged to form a strictly contiguous sequence. A contiguous sequence is a set of numbers that are in consecutive order (e.g., [1, 2, 3, 4]). Example 1: Input: 5 4 3 3 1 1 Output: 2 Explanation: The largest subarray that can be rearranged to form a contiguous sequence here is {4, 3} , which can be rearranged to {3, 4} . Best Technique – Brute Force Approach This problem can be solved in several ways. Let's start by breaking down the brute force approach, which works by checking all possible subarrays of the given array. It’s not the most efficient solution, but it’s easy to understand and implement. The key idea is: For every possible subarray, check if it can be rearranged into a contiguous sequence. A contiguous...