Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views22 pages

Leetcode 75 With Main Scanner

The document contains Java code implementations for various algorithms and data structures, including solutions for problems like Two Sum, Three Sum, Best Time to Buy Stock, Maximum Subarray Sum, and more. Each section provides a brief description of the problem, followed by the code that reads input, processes the data, and outputs the result. The document covers a range of topics from arrays and strings to sorting and searching algorithms.

Uploaded by

Varsha Velavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Leetcode 75 With Main Scanner

The document contains Java code implementations for various algorithms and data structures, including solutions for problems like Two Sum, Three Sum, Best Time to Buy Stock, Maximum Subarray Sum, and more. Each section provides a brief description of the problem, followed by the code that reads input, processes the data, and outputs the result. The document covers a range of topics from arrays and strings to sorting and searching algorithms.

Uploaded by

Varsha Velavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

ARRAYS

1. TWO SUM

import java.util.Scanner;

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input size of array

int n = sc.nextInt();

// Input array elements

int[] nums = new int[n];

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt();

// Input target

int target = sc.nextInt();

// Store result in an array

int[] result = new int[2];

// Find the first matching pair

for (int i = 0; i < nums.length; i++) {

for (int j = i + 1; j < nums.length; j++) {


if (nums[i] + nums[j] == target) {

result[0] = i;

result[1] = j;

System.out.println(Arrays.toString(result)); // Print as [0, 1]

return;

sc.close();

15 . THREE SUM
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Read size of array

int n = sc.nextInt();

int[] nums = new int[n];

// Read array elements

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt();

}
// Sort the array first

Arrays.sort(nums);

List<List<Integer>> result = new ArrayList<>();

// Loop through the array

for (int i = 0; i < n - 2; i++) {

// Skip duplicates for i

if (i > 0 && nums[i] == nums[i - 1]) continue;

int left = i + 1;

int right = n - 1;

while (left < right) {

int sum = nums[i] + nums[left] + nums[right];

if (sum == 0) {

result.add(Arrays.asList(nums[i], nums[left], nums[right]));

// Move left and right to skip duplicates

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++; // Increase sum

} else {

right--; // Decrease sum


}

// Print the result

for (List<Integer> triplet : result) {

System.out.println(triplet);

sc.close();

121. BEST TIME TO BUT STOCK AND SELL

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Read input size

int n = sc.nextInt();

int[] prices = new int[n];

// Read prices

for (int i = 0; i < n; i++) {

prices[i] = sc.nextInt();

}
int maxPro = 0;

int minPrice = Integer.MAX_VALUE;

for (int i = 0; i < prices.length; i++) {

minPrice = Math.min(minPrice, prices[i]);

maxPro = Math.max(maxPro, prices[i] - minPrice);

System.out.println(maxPro);

53.MAXIMUN SUM ARRAY


import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Take array size input

int n = sc.nextInt();

int[] nums = new int[n];

// Read array elements

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt();

}
int ans = Integer.MIN_VALUE; // ✅ Start with the smallest possible number

int sum = 0; // ✅ Holds current subarray sum

for (int i = 0; i < nums.length; i++) {

sum = Math.max(nums[i], sum + nums[i]); // ✅ Either start new subarray or extend

ans = Math.max(ans, sum); // ✅ Track the maximum subarray sum found

System.out.println(ans); // ✅ Print final result

88.MERGE SORTED ARRAY


import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Read sizes

int m = sc.nextInt(); // Actual elements in nums1

int n = sc.nextInt(); // Elements in nums2

int[] nums1 = new int[m + n]; // nums1 has extra space

int[] nums2 = new int[n];

// Input first m elements of nums1

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

nums1[i] = sc.nextInt();
}

// Input all elements of nums2

for (int i = 0; i < n; i++) {

nums2[i] = sc.nextInt();

// Pointers

int p1 = m - 1; // last index of nums1 actual data

int p2 = n - 1; // last index of nums2

int i = m + n - 1; // last index of nums1 full

// Merge from end

while (p2 >= 0) {

if (p1 >= 0 && nums1[p1] > nums2[p2]) {

nums1[i--] = nums1[p1--];

} else {

nums1[i--] = nums2[p2--];

// Output merged array

for (int x : nums1) {

System.out.print(x + " ");

}
217.CONTAINS DUPLICATE
import java.util.Scanner;

import java.util.Arrays;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Solution obj = new Solution();

int n = sc.nextInt(); // Read size of array

int[] nums = new int[n];

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt(); // Read array elements

System.out.println(obj.containsDuplicate(nums)); // Print only true or false

sc.close();

public boolean containsDuplicate(int[] nums) {

if (nums == null || nums.length == 0) return false;

Arrays.sort(nums); // Sort the array

for (int i = 0; i < nums.length - 1; i++) {


if (nums[i] == nums[i + 1]) {

return true; // Found duplicate

return false; // No duplicates

}
238.PRODUCT OF ARRAY EXCEPT SHELF
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Read array size

int n = sc.nextInt();

int[] nums = new int[n];

// Read array elements

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt();

int[] ans = new int[n];

int[] prefix = new int[n];

int[] suffix = new int[n];

// prefix[i] = product of all elements before index i


prefix[0] = 1;

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

prefix[i] = prefix[i - 1] * nums[i - 1];

// suffix[i] = product of all elements after index i

suffix[n - 1] = 1;

for (int i = n - 2; i >= 0; i--) {

suffix[i] = suffix[i + 1] * nums[i + 1];

// ans[i] = prefix[i] * suffix[i]

for (int i = 0; i < n; i++) {

ans[i] = prefix[i] * suffix[i];

// Print the result array

for (int num : ans) {

System.out.print(num + " ");

sc.close();

11. CONTAINER WITH MOST WATER


import java.util.Scanner;

public class MaxWaterContainer {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Step 1: Input the number of vertical lines (heights)

System.out.print("Enter number of heights: ");

int n = sc.nextInt(); // example: 9

int[] height = new int[n];

// Step 2: Input the height of each vertical line

System.out.println("Enter heights:");

for (int i = 0; i < n; i++) {

height[i] = sc.nextInt(); // example input: 1 8 6 2 5 4 8 3 7

// Step 3: Initialize two pointers

int l = 0; // Start from leftmost line

int r = n - 1; // Start from rightmost line

int ans = 0; // To store the maximum area

// Step 4: Move the two pointers toward each other

while (l < r) {

// Find the shorter height between the two lines

int minHeight = Math.min(height[l], height[r]);

// Calculate the area between the two lines

int area = minHeight * (r - l); // width = r - l

// Update the answer if current area is greater


ans = Math.max(ans, area);

// Move the pointer pointing to the shorter line

if (height[l] < height[r]) {

l++; // move left pointer to the right

} else {

r--; // move right pointer to the left

// Step 5: Print the maximum area found

System.out.println("Maximum area: " + ans);

}
48.ROATATE IMAGE
import java.util.Scanner;

public class RotateMatrix {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input: matrix size

System.out.print("Enter size of square matrix (n): ");

int n = sc.nextInt();

int[][] matrix = new int[n][n];

// Input: matrix elements

System.out.println("Enter matrix elements:");


for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

matrix[i][j] = sc.nextInt();

// Step 1: Reverse rows (top ↔ bottom)

for (int i = 0, j = n - 1; i < j; ++i, --j) {

int[] temp = matrix[i];

matrix[i] = matrix[j];

matrix[j] = temp;

// Step 2: Transpose (swap elements diagonally)

for (int i = 0; i < n; ++i) {

for (int j = i + 1; j < n; ++j) {

int temp = matrix[i][j];

matrix[i][j] = matrix[j][i];

matrix[j][i] = temp;

// Output: rotated matrix

System.out.println("Rotated Matrix (90° Clockwise):");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

System.out.print(matrix[i][j] + " ");

}
System.out.println();

sc.close();

STRINGS
20.VALID PARENTHESIS
import java.util.Scanner;

import java.util.Stack;

public class ValidParentheses {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a string with brackets: ");

String s = sc.nextLine();

Stack<Character> stack = new Stack<>();

for (char c : s.toCharArray()) {

if (c == '(' || c == '{' || c == '[') {

stack.push(c); // Push open brackets

} else {

if (stack.isEmpty()) {

System.out.println("false");

return;

char top = stack.pop();


if ((c == ')' && top != '(') ||

(c == '}' && top != '{') ||

(c == ']' && top != '[')) {

System.out.println("false");

return;

// If stack is empty at the end, it's valid

System.out.println(stack.isEmpty() ? "true" : "false");

sc.close();

125.VALID PANLIDROME
import java.util.Scanner;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = sc.nextLine();

// Convert to lowercase and remove non-alphanumeric characters

String s = input.toLowerCase().replaceAll("[^a-z0-9]", "");

int left = 0;

int right = s.length() - 1;


while (left < right) {

if (s.charAt(left) != s.charAt(right)) {

System.out.println("false");

return;

left++;

right--;

System.out.println("true");

242.VALID ANAGRAM
import java.util.Arrays;

import java.util.Scanner;

public class Solution {

public static boolean isAnagram(String s, String t) {

if (s.length() != t.length()) {

return false;

char[] charS = s.toCharArray();

char[] charT = t.toCharArray();

Arrays.sort(charS);

Arrays.sort(charT);
return Arrays.equals(charS, charT);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter first string: ");

String s = sc.nextLine();

System.out.print("Enter second string: ");

String t = sc.nextLine();

boolean result = isAnagram(s, t);

if (result)

System.out.println("The strings are anagrams.");

else

System.out.println("The strings are NOT anagrams.");

5. LONGETS PANLINDROME SUBSTRING


import java.util.Scanner;

public class LongestPalindrome {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the string: ");


String s = sc.nextLine();

String result = longestPalindrome(s);

System.out.println("Longest Palindromic Substring: " + result);

public static String longestPalindrome(String s) {

if (s == null || s.length() < 1) return "";

int start = 0, end = 0;

for (int i = 0; i < s.length(); i++) {

int len1 = expandAroundCenter(s, i, i); // Odd length

int len2 = expandAroundCenter(s, i, i + 1); // Even length

int len = Math.max(len1, len2);

if (len > end - start) {

start = i - (len - 1) / 2;

end = i + len / 2;

return s.substring(start, end + 1);

// Made public and static

public static int expandAroundCenter(String s, int left, int right) {

while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;

right++;

return right - left - 1;

28.FOND THE INDEX OF THE FIRST OCC


import java.util.Scanner;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String haystack = sc.nextLine();

String needle = sc.nextLine();

int m = haystack.length();

int n = needle.length();

int index = -1;

for (int i = 0; i <= m - n; i++) {

if (haystack.substring(i, i + n).equals(needle)) {

index = i;

break;

System.out.println(index);
}

14.LONGEST COMMON PREFIX


import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt(); // Number of strings

sc.nextLine(); // Consume newline

String[] strs = new String[n];

for (int i = 0; i < n; i++) {

strs[i] = sc.nextLine();

if (n == 0) {

System.out.println("");

return;

Arrays.sort(strs);

String str1 = strs[0];

String str2 = strs[n - 1];

int index = 0;

while (index < str1.length() && index < str2.length()) {


if (str1.charAt(index) == str2.charAt(index)) {

index++;

} else {

break;

System.out.println(str1.substring(0, index));

459. REPAETAED SUBSTRING PATTERN


import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String s = sc.nextLine();

boolean result = false;

for (int i = 1; i <= s.length() / 2; i++) {

String sub = s.substring(0, i);

if (s.length() % i == 0) {

StringBuilder sb = new StringBuilder();

int repeat = s.length() / i;

for (int j = 0; j < repeat; j++) {

sb.append(sub);

}
if (sb.toString().equals(s)) {

result = true;

break;

System.out.println(result);

You might also like