Coding Problems Cheatsheet

Category Problem Key Concepts/Strategies Detailed Explanation Code Example Arrays & Hashing Contains Duplicate Use a set to track seen numbers Iterate through the array, adding each element to the set; return true if an element is already in the set. Valid Anagram Use a hashmap to count character frequencies Count characters in both strings using hashmaps and compare the counts. Two Sum Use a hashmap to store indices of elements Iterate through the array, for each element, check if the complement (target - element) exists in the hashmap. Two Pointers Valid Palindrome Use two pointers to compare characters from both ends Initialize two pointers at the beginning and end of the string, move towards the center, and compare characters. 3Sum Sort the array, use two pointers to find triplets After sorting, fix one element and use two pointers to find pairs that sum up to the target value. Container With Most Water Use two pointers from both ends, move towards the center Start with two pointers at the ends of the array, calculate area, and move the pointer pointing to the shorter line. Sliding Window Best Time to Buy and Sell Stock Track the minimum price and maximum profit Iterate through prices, keeping track of the minimum price so far and calculating the maximum profit at each step. Longest Substring Without Repeating Characters Use a sliding window and a set to track characters Use a set to keep track of characters in the current window, move the window if a duplicate is found. Stack Valid Parentheses Use a stack to match opening and closing brackets Push opening brackets onto the stack, pop for closing brackets, ensuring they match. Binary Search Search in Rotated Sorted Array Modify binary search to handle rotation Determine which half is sorted, then use binary search logic on the sorted half. Find Minimum in Rotated Sorted Array Use binary search with rotation consideration Similar to searching in a rotated array, adjust the binary search to find the minimum element. Linked List Reverse Linked List Iterate and reverse pointers Use three pointers to reverse the direction of the list iteratively. Merge Two Sorted Lists Use a dummy node to merge iteratively Use a dummy node to simplify merging two lists, iteratively comparing and linking nodes. Reorder List Find middle, reverse second half, merge Split the list, reverse the second half, and merge the two halves by alternating nodes. Trees Binary Tree Inorder Traversal Use recursion or a stack Traverse left subtree, visit the node, then traverse the right subtree. Validate Binary Search Tree Use in-order traversal to check order Perform an in-order traversal and ensure each value is greater than the previous one. Same Tree Use recursion to compare nodes Recursively compare corresponding nodes in both trees. Tries Implement Trie (Prefix Tree) Use a TrieNode class to insert and search Use a nested TrieNode class to represent nodes, with methods for insert, search, and startsWith. Dynamic Programming Climbing Stairs Use DP array or memoization Use an array where each entry represents the number of ways to reach that step. House Robber Use a DP array to track maximum loot Use a DP array where each entry represents the maximum amount of money that can be robbed up to that house. Coin Change Use a DP array to track the minimum coins Use a DP array where each entry represents the minimum number of coins needed for that amount. Graphs Number of Islands Use DFS/BFS to mark visited islands Use DFS or BFS to traverse and mark all connected lands (islands) as visited. Clone Graph Use DFS/BFS and a hashmap for copies Use DFS or BFS with a hashmap to store already cloned nodes. Course Schedule Use DFS to detect cycles Perform a DFS and use a state array to detect cycles in the graph. Intervals Merge Intervals Sort intervals, then merge overlapping ones Sort intervals by start time, then iterate through and merge overlapping intervals. Insert Interval Insert and merge as necessary Insert the new interval into the list, then merge overlapping intervals. Meeting Rooms Sort intervals and check for overlaps Sort intervals by start time, use a min-heap to track end times of ongoing meetings. Strings Longest Substring Without Repeating Characters Use sliding window and a hashmap Use a sliding window to maintain a window of unique characters, updating the start of the window when a duplicate is found. Longest Palindromic Substring Use DP or expand around center approach Use dynamic programming to track palindromes or expand around each character to find the longest palindrome. Longest Common Prefix Compare characters of each string Compare characters of each string one by one until a mismatch is found. Backtracking Subsets Use backtracking to generate all subsets Recursively build subsets, choosing to include or exclude each element. Combination Sum Use backtracking to find combinations Recursively build combinations, subtracting from the target, and avoiding duplicates. Permutations Use backtracking to generate permutations Recursively generate permutations by swapping elements. Heap / Priority Queue Top K Frequent Elements Use a hashmap and a heap Use a hashmap to count frequencies, then use a heap to find the top K elements. Find Median from Data Stream Use two heaps to maintain the median Use a max-heap for the lower half and a min-heap for the upper half of the data stream. Greedy Best Time to Buy and Sell Stock II Sum up all the increasing differences Iterate through the array, summing up all positive differences between consecutive days. Jump Game Track the farthest reach possible Iterate through the array, updating the maximum reachable index and checking if the end is reachable. Bit Manipulation Single Number Use XOR to find the unique number XOR all elements, as XOR of two identical numbers is zero, and XOR of a number with zero is the number itself. Matrix Set Matrix Zeroes Use first row/column as markers Use the first row and column to mark zero rows and columns, then iterate and set zeros accordingly. Spiral Matrix Traverse in layers and change directions Use loops to traverse the matrix in a spiral order, changing direction at boundaries. Rotate Image Transpose and then reverse rows Transpose the matrix (swap rows and columns) and then reverse each row. Miscellaneous LRU Cache Use an ordered dictionary Use an ordered dictionary to maintain insertion order and implement LRU logic. Min Stack Use two stacks for value and minimum Use one stack for all values and another stack to keep track of minimum values.

July 7, 2024 · 6 min · 1081 words · PandaC

Understanding Usecase Diagram

What is a Use Case Diagram? A use case diagram is a type of drawing that shows how different people (called “actors”) interact with a system (like a software program or website). It’s a way to show what the system does and who uses it. Key Notions (Symbols) in a Use Case Diagram: Actors: Stick Figure: Represents a person or thing that interacts with the system. For example, a student, teacher, or librarian. Use Cases: ...

June 17, 2024 · 3 min · 458 words · PandaC

Understanding UML Diagrams

Unified Modelling Language (UML) is a standardised way to visualize the design of a system. UML diagrams can be categorized into two main types: Structural Diagrams and Behavioral Diagrams. Understanding these categories helps in effectively modeling both the static and dynamic aspects of a system. Structural Diagrams Structural diagrams represent the static aspects of a system. They show the system’s classes, objects, and relationships. Here are the key types of structural diagrams: ...

June 17, 2024 · 3 min · 626 words · PandaC

Consuming REST Services in Spring Boot: RestTemplate, WebClient, and Feign Client

Spring Boot provides several robust options for consuming RESTful web services. In this blog post, we will explore three primary methods: RestTemplate, WebClient, and Feign Client. Each approach offers unique features and benefits suited for different use cases. 1. RestTemplate Description: RestTemplate is a synchronous client for performing HTTP requests. It is simple to use and ideal for applications where synchronous calls are sufficient. Setup and Usage: Add Dependency: To use RestTemplate, add the following dependency to your pom.xml: ...

June 10, 2024 · 2 min · 411 words · PandaC

Asynchronous processing in a Spring Boot REST

Configuring asynchronous processing in a Spring Boot REST application allows you to handle requests without blocking the main thread, improving performance and responsiveness. Here’s a step-by-step guide to enable and configure asynchronous processing in your Spring Boot REST application: 1. Enable Async Support First, enable asynchronous processing by adding the @EnableAsync annotation to your Spring Boot application class or any other configuration class. import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } } 2. Configure an Async Executor Define a ThreadPoolTaskExecutor bean to handle async tasks. This executor can be configured to manage the number of threads, queue capacity, and other parameters. ...

June 10, 2024 · 4 min · 789 words · PandaC

Internationalization (i18n) in Spring Boot with Thymeleaf

Internationalization (i18n) in Spring Boot with Thymeleaf allows you to create web applications that can support multiple languages. This involves setting up message resource files for different languages and configuring your application to use them. Here’s a step-by-step guide to set up i18n in a Spring Boot application using Thymeleaf: Step 1: Add Dependencies Ensure you have the necessary dependencies in your pom.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Step 2: Create Message Resource Files Create message resource files for each language you want to support. For example, create messages.properties for the default language, messages_fr.properties for French, and messages_es.properties for Spanish. ...

June 10, 2024 · 3 min · 527 words · PandaC

Spring Boot 3 Rest: Error Handling

Handling exceptions gracefully in a Spring Boot 3 REST application is crucial for providing clear and consistent error responses to the clients. In this section, we’ll explore how to handle exceptions for REST controllers using @ControllerAdvice and @ExceptionHandler annotations, and customize error responses. Setting Up the Project Ensure you have the necessary dependencies in your pom.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Step 1: Create a Custom Exception Define a custom exception that can be thrown by your REST controllers: ...

June 10, 2024 · 5 min · 1021 words · PandaC

Spring Boot 3 with Thymeleaf: Error Handling

In modern web applications, providing clear and user-friendly error messages is crucial for a good user experience. In this blog post, we’ll explore how to customize error handling in a Spring Boot 3 application using Thymeleaf. We’ll look at how to create custom error attributes, define a global error controller, and design a custom error page with Thymeleaf. Setting Up the Project First, ensure your Spring Boot 3 project is set up with the necessary dependencies. We’ll need spring-boot-starter-thymeleaf for the Thymeleaf integration and spring-boot-starter-web for creating the web application. ...

June 10, 2024 · 5 min · 905 words · PandaC

Using Thymeleaf with Spring Boot

Thymeleaf is a modern server-side Java template engine for web and standalone environments. It is particularly well-suited for Spring Boot applications, offering a natural way to create dynamic web pages. In this blog post, we’ll explore how to integrate Thymeleaf with Spring Boot, create dynamic templates, and use Thymeleaf’s powerful features to build a simple web application. Setting Up Thymeleaf with Spring Boot Step 1: Create a Spring Boot Project Start by creating a new Spring Boot project using Spring Initializr or your preferred method. Make sure to include the Spring Web and Thymeleaf dependencies. ...

June 9, 2024 · 4 min · 746 words · PandaC

Spring Boot Devtools to Speed Up Development

Spring Boot Devtools is a powerful tool that significantly improves the development experience by providing features like automatic restarts, live reload, and configurations that are optimized for development. In this blog post, we’ll explore how to set up and use Spring Boot Devtools to speed up your development workflow. Why Use Spring Boot Devtools? Spring Boot Devtools enhances the development process in several ways: Automatic Restarts: Automatically restarts your application whenever files on the classpath change, saving you the hassle of manually restarting the server. Live Reload: Integrates with LiveReload to refresh the browser when resources change, providing instant feedback on your changes. Development-Time Configurations: Applies specific settings that make development easier, like disabling template caching and enabling debug logging. Setting Up Spring Boot Devtools Adding Devtools Dependency First, you need to add the Spring Boot Devtools dependency to your project. This can be done by adding the following dependency to your pom.xml if you are using Maven: ...

June 9, 2024 · 4 min · 661 words · PandaC