0% found this document useful (0 votes)
18 views17 pages

Phone Pe

The document contains multiple Java classes implementing solutions to various algorithmic problems, including cycle detection in graphs, longest common subsequence, two-sum, valid parentheses, and more. Each class provides methods to solve the respective problem using different algorithms and data structures. The document serves as a collection of coding challenges and their solutions, primarily focusing on common interview questions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views17 pages

Phone Pe

The document contains multiple Java classes implementing solutions to various algorithmic problems, including cycle detection in graphs, longest common subsequence, two-sum, valid parentheses, and more. Each class provides methods to solve the respective problem using different algorithms and data structures. The document serves as a collection of coding challenges and their solutions, primarily focusing on common interview questions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

// Detect Cycle in Undirected Graph using DFS

class DetectCycleGraphSolution {
public boolean hasCycle(int V, List<List<Integer>> adj) {
boolean[] visited = new boolean[V];
for (int i = 0; i < V; i++) {
if (!visited[i]) {
if (dfs(i, -1, visited, adj)) return true;
}
}
return false;
}

private boolean dfs(int node, int parent, boolean[] visited, List<List<Integer>>


adj) {
visited[node] = true;
for (int neighbor : [Link](node)) {
if (!visited[neighbor]) {
if (dfs(neighbor, node, visited, adj)) return true;
} else if (neighbor != parent) {
return true;
}
}
return false;
}
}

// Longest Common Subsequence (LC 1143)


class LongestCommonSubsequenceSolution {
public int longestCommonSubsequence(String text1, String text2) {
int m = [Link](), n = [Link]();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if ([Link](i - 1) == [Link](j - 1))
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = [Link](dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
}
// Two Sum (LC 1)

class TwoSumSolution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int complement = target - nums[i];
if ([Link](complement)) {
return new int[]{[Link](complement), i};
}
[Link](nums[i], i);
}
return new int[]{};
}
}

// Valid Parentheses (LC 20)

class ValidParenthesesSolution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : [Link]()) {
if (c == '(' || c == '{' || c == '[') {
[Link](c);
} else {
if ([Link]()) return false;
char top = [Link]();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) return false;
}
}
return [Link]();
}
}

// Merge Two Sorted Lists (LC 21)

class MergeTwoSortedListsSolution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (l1 != null && l2 != null) {
if ([Link] < [Link]) {
[Link] = l1;
l1 = [Link];
} else {
[Link] = l2;
l2 = [Link];
}
current = [Link];
}
[Link] = (l1 != null) ? l1 : l2;
return [Link];
}
}

// Binary Tree Inorder Traversal (LC 94)

class BinaryTreeInorderTraversalSolution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || ![Link]()) {
while (current != null) {
[Link](current);
current = [Link];
}
current = [Link]();
[Link]([Link]);
current = [Link];
}
return result;
}
}

// Maximum Subarray (LC 53)

class MaxSubarraySolution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currSum = nums[0];
for (int i = 1; i < [Link]; i++) {
currSum = [Link](nums[i], currSum + nums[i]);
maxSum = [Link](maxSum, currSum);
}
return maxSum;
}
}

// Climbing Stairs (LC 70)

class ClimbingStairsSolution {
public int climbStairs(int n) {
if (n <= 2) return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int temp = a + b;
a = b;
b = temp;
}
return b;
}
}

// Number of Islands (LC 200)

class NumberOfIslandsSolution {
public int numIslands(char[][] grid) {
int count = 0;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}

private void dfs(char[][] grid, int i, int j) {


if (i < 0 || j < 0 || i >= [Link] || j >= grid[0].length || grid[i][j] !=
'1')
return;
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
}

// Coin Change (LC 322)


class CoinChangeSolution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
[Link](dp, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = [Link](dp[i], dp[i - coin] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}

// Helper classes for TreeNode and ListNode


class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

// LC 200 - Number of Islands (DFS)

public int numIslands(char[][] grid) {


int count = 0;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}

private void dfs(char[][] grid, int i, int j) {


if (i < 0 || i >= [Link] || j < 0 || j >= grid[0].length || grid[i][j] ==
'0') return;
grid[i][j] = '0';
dfs(grid, i+1, j); dfs(grid, i-1, j); dfs(grid, i, j+1); dfs(grid, i, j-1);
}

// LC 207 - Course Schedule (Topological Sort – DFS)

public boolean canFinish(int numCourses, int[][] prerequisites) {


List<Integer>[] graph = new List[numCourses];
for (int i = 0; i < numCourses; i++) graph[i] = new ArrayList<>();
for (int[] p : prerequisites) graph[p[0]].add(p[1]);
int[] visited = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (hasCycle(graph, visited, i)) return false;
}
return true;
}

private boolean hasCycle(List<Integer>[] graph, int[] visited, int course) {


if (visited[course] == 1) return true;
if (visited[course] == 2) return false;
visited[course] = 1;
for (int pre : graph[course]) {
if (hasCycle(graph, visited, pre)) return true;
}
visited[course] = 2;
return false;
}

// LC 133 - Clone Graph

class Node {
public int val;
public List<Node> neighbors;
public Node(int val) {
[Link] = val;
[Link] = new ArrayList<>();
}
}

private Map<Node, Node> visited = new HashMap<>();

public Node cloneGraph(Node node) {


if (node == null) return null;
if ([Link](node)) return [Link](node);
Node copy = new Node([Link]);
[Link](node, copy);
for (Node neighbor : [Link]) {
[Link](cloneGraph(neighbor));
}
return copy;
}

// LC 994 - Rotting Oranges (Multi-source BFS)

public int orangesRotting(int[][] grid) {


Queue<int[]> q = new LinkedList<>();
int fresh = 0, rows = [Link], cols = grid[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 2) [Link](new int[]{i, j});
else if (grid[i][j] == 1) fresh++;
}
}
int time = 0;
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
while (![Link]() && fresh > 0) {
int size = [Link]();
for (int i = 0; i < size; i++) {
int[] cur = [Link]();
for (int[] d : dirs) {
int x = cur[0] + d[0], y = cur[1] + d[1];
if (x >= 0 && y >= 0 && x < rows && y < cols && grid[x][y]
== 1) {
grid[x][y] = 2;
fresh--;
[Link](new int[]{x, y});
}
}
}
time++;
}
return fresh == 0 ? time : -1;
}

// LC 53 - Maximum Subarray (Kadane's Algorithm)

class MaxSubarraySolution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currSum = nums[0];
for (int i = 1; i < [Link]; i++) {
currSum = [Link](nums[i], currSum + nums[i]);
maxSum = [Link](maxSum, currSum);
}
return maxSum;
}
}

// LC 70 - Climbing Stairs

class ClimbingStairsSolution {
public int climbStairs(int n) {
if (n <= 2) return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int temp = a + b;
a = b;
b = temp;
}
return b;
}
}

// LC 198 - House Robber

class HouseRobberSolution {
public int rob(int[] nums) {
if ([Link] == 0) return 0;
if ([Link] == 1) return nums[0];
int[] dp = new int[[Link]];
dp[0] = nums[0];
dp[1] = [Link](nums[0], nums[1]);
for (int i = 2; i < [Link]; i++) {
dp[i] = [Link](dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[[Link] - 1];
}
}

// LC 322 - Coin Change

class CoinChangeSolution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
[Link](dp, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = [Link](dp[i], dp[i - coin] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}

// LC 72 - Edit Distance

class EditDistanceSolution {
public int minDistance(String word1, String word2) {
int m = [Link](), n = [Link]();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = i;
for (int j = 0; j <= n; j++) dp[0][j] = j;

for (int i = 1; i <= m; i++) {


for (int j = 1; j <= n; j++) {
if ([Link](i - 1) == [Link](j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + [Link](dp[i - 1][j - 1],
[Link](dp[i - 1][j], dp[i][j - 1]));
}
}
}
return dp[m][n];
}
}

// LC 300 - Longest Increasing Subsequence

class LongestIncreasingSubsequenceSolution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[[Link]];
int len = 0;
for (int num : nums) {
int i = [Link](dp, 0, len, num);
if (i < 0) i = -(i + 1);
dp[i] = num;
if (i == len) len++;
}
return len;
}
}

// LC 516 - Longest Palindromic Subsequence

class LongestPalindromicSubsequenceSolution {
public int longestPalindromeSubseq(String s) {
int n = [Link]();
int[][] dp = new int[n][n];
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < n; j++) {
if ([Link](i) == [Link](j)) {
dp[i][j] = 2 + dp[i + 1][j - 1];
} else {
dp[i][j] = [Link](dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
}

// LC 1 - Two Sum

}
// LC 11 - Container With Most Water
class ContainerWithMostWaterSolution {
public int maxArea(int[] height) {
int left = 0, right = [Link] - 1, max = 0;
while (left < right) {
int area = (right - left) * [Link](height[left], height[right]);
max = [Link](max, area);
if (height[left] < height[right]) left++;
else right--;
}
return max;
}
}

// LC 15 – 3Sum

class ThreeSumSolution {
public List<List<Integer>> threeSum(int[] nums) {
[Link](nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < [Link] - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = [Link] - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
[Link]([Link](nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++; right--;
} else if (sum < 0) left++;
else right--;
}
}
return res;
}
}

// LC 76 - Minimum Window Substring

class MinimumWindowSubstringSolution {
public String minWindow(String s, String t) {
if ([Link]() < [Link]()) return "";
Map<Character, Integer> map = new HashMap<>();
for (char c : [Link]()) [Link](c, [Link](c, 0) + 1);
int left = 0, minLen = Integer.MAX_VALUE, count = [Link]();
int start = 0;
for (int right = 0; right < [Link](); right++) {
if ([Link]([Link](right))) {
if ([Link]([Link](right)) > 0) count--;
[Link]([Link](right), [Link]([Link](right)) - 1);
}
while (count == 0) {
if (right - left + 1 < minLen) {
minLen = right - left + 1;
start = left;
}
if ([Link]([Link](left))) {
[Link]([Link](left), [Link]([Link](left)) + 1);
if ([Link]([Link](left)) > 0) count++;
}
left++;
}
}
return minLen == Integer.MAX_VALUE ? "" : [Link](start, start +
minLen);
}
}

// LC 49 - Group Anagrams

class GroupAnagramsSolution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] ch = [Link]();
[Link](ch);
String key = new String(ch);
[Link](key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>([Link]());
}
}

// 🌳 Trees & Binary Search

// LC 94 - Binary Tree Inorder Traversal

class BinaryTreeInorderTraversalSolution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || ![Link]()) {
while (current != null) {
[Link](current);
current = [Link];
}
current = [Link]();
[Link]([Link]);
current = [Link];
}
return result;
}
}

// LC 98 - Validate Binary Search Tree

class ValidateBSTSolution {
public boolean isValidBST(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValid(TreeNode node, long min, long max) {


if (node == null) return true;
if ([Link] <= min || [Link] >= max) return false;
return isValid([Link], min, [Link]) && isValid([Link], [Link], max);
}
}

// LC 235 - Lowest Common Ancestor of BST

class LcaBSTSolution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if ([Link] > [Link] && [Link] > [Link]) return
lowestCommonAncestor([Link], p, q);
if ([Link] < [Link] && [Link] < [Link]) return
lowestCommonAncestor([Link], p, q);
return root;
}
}

// LC 230 - Kth Smallest Element in a BST

class KthSmallestBSTSolution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
while (true) {
while (root != null) {
[Link](root);
root = [Link];
}
root = [Link]();
if (--k == 0) return [Link];
root = [Link];
}
}
}

// LC 34 - Find First and Last Position of Element in Sorted Array

class FirstLastPositionSortedArraySolution {
public int[] searchRange(int[] nums, int target) {
int first = findBound(nums, target, true);
if (first == -1) return new int[]{-1, -1};
int last = findBound(nums, target, false);
return new int[]{first, last};
}

private int findBound(int[] nums, int target, boolean isFirst) {


int left = 0, right = [Link] - 1, bound = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
bound = mid;
if (isFirst) right = mid - 1;
else left = mid + 1;
} else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return bound;
}
}

// LC 21 - Merge Two Sorted Lists

class MergeTwoSortedListsSolution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (l1 != null && l2 != null) {
if ([Link] < [Link]) {
[Link] = l1;
l1 = [Link];
} else {
[Link] = l2;
l2 = [Link];
}
current = [Link];
}
[Link] = (l1 != null) ? l1 : l2;
return [Link];
}
}

// LC 206 - Reverse Linked List

class ReverseLinkedListSolution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = [Link];
[Link] = prev;
prev = head;
head = next;
}
return prev;
}
}
// LC 141 - Linked List Cycle

class LinkedListCycleSolution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && [Link] != null) {
slow = [Link];
fast = [Link];
if (slow == fast) return true;
}
return false;
}
}

// LC 19 - Remove Nth Node From End of List

class RemoveNthNodeFromEndSolution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
[Link] = head;
ListNode first = dummy, second = dummy;
for (int i = 0; i <= n; i++) first = [Link];
while (first != null) {
first = [Link];
second = [Link];
}
[Link] = [Link];
return [Link];
}
}

LC 20 - Valid Parentheses

class ValidParenthesesSolution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : [Link]()) {
if (c == '(' || c == '{' || c == '[') {
[Link](c);
} else {
if ([Link]()) return false;
char top = [Link]();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) return false;
}
}
return [Link]();
}
}

LC 232 - Implement Queue Using Stacks

class MyQueue {
Stack<Integer> input = new Stack<>();
Stack<Integer> output = new Stack<>();

public void push(int x) {


[Link](x);
}

public int pop() {


peek();
return [Link]();
}

public int peek() {


if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}

public boolean empty() {


return [Link]() && [Link]();
}
}

LC 739 - Daily Temperatures

class DailyTemperaturesSolution {
public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[[Link]];
Stack<Integer> stack = new Stack<>();

for (int i = 0; i < [Link]; i++) {


while (![Link]() && temperatures[i] >
temperatures[[Link]()]) {
int prevIndex = [Link]();
result[prevIndex] = i - prevIndex;
}
[Link](i);
}

return result;
}

You might also like