Detect Cycle in a Directed Graph 1

Title: Detect Cycle in a Directed Graph Source: www.geeksforgeeks.org Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must ...

Fancy Numbers

Title: Check if a given number is Fancy Source: www.geeksforgeeks.org A fancy number is one which when rotated 180 degrees is the same. Given a number, find whether it is fancy or not. 180 degree rotations of 6, 9, 1, 0 and 8 are 9, 6, 1, 0 and 8 respectively Examples: Input: num = ...

Design a tiny URL or URL shortener 27

Title: How to design a tiny URL or URL shortener? Source: www.geeksforgeeks.org How to design a system that takes big URLs like “http://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/” and converts them into a short 6 character URL. It is given that URLs are stored in database and every URL has an associated integer id. One important thing to note is, ...

Contains Duplicate

Title: Contains Duplicate Source: leetcode.com Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Java solution Java /* https://leetcode.com/problems/contains-duplicate/ */ import java.util.HashSet; public class ContainsDuplicate { public ...

Container With Most Water

Title: Container With Most Water Source: leetcode.com Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such ...

Clone Graph

Title: Clone Graph Source: leetcode.com Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely. Java solution Java /* https://leetcode.com/problems/clone-graph/ */ import java.util.HashMap; import java.util.List; import java.util.ArrayList; public class CloneGraph { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node==null) return null; HashMap<Integer, UndirectedGraphNode> visited = ...

Bulls and Cows

Title: Bulls and Cows Source: leetcode.com You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret ...