KEMBAR78
Indrajith N (23MCA513) Leetcode Assignment | PDF | String (Computer Science) | Integer (Computer Science)
0% found this document useful (0 votes)
17 views33 pages

Indrajith N (23MCA513) Leetcode Assignment

The document contains a series of programming problems and their corresponding solutions, primarily in Python and Java. Each problem is presented with a description, the code to solve it, and an indication of the expected output. Topics covered include string manipulation, array processing, mathematical computations, and algorithmic challenges.

Uploaded by

indrajithn48
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)
17 views33 pages

Indrajith N (23MCA513) Leetcode Assignment

The document contains a series of programming problems and their corresponding solutions, primarily in Python and Java. Each problem is presented with a description, the code to solve it, and an indication of the expected output. Topics covered include string manipulation, array processing, mathematical computations, and algorithmic challenges.

Uploaded by

indrajithn48
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
You are on page 1/ 33

LEET CODE PROGRAMS

Name - INDRAJITH N
Reg.no - 23MCA513
Class - II-MCA
Date – 17.10.2024
1.Given a pattern and a string s, find if s follows the same pattern.
Program:
pattern = input("Enter the pattern: ")
s = input("Enter the string: ")
def wordPattern(pattern, s):
words = s.split()
mapping = {}
for i in range(len(pattern)):
p, w = pattern[i], words[i]
if p not in mapping:
if w in mapping.values():
return False
mapping[p] = w
elif mapping[p] != w:
return False
return True
print(wordPattern(pattern, s))

output:
2.Write a function to find the longest common prefix string amongst an
array of strings.
Program:
def longest_common_prefix(strs):
if not strs:
return ""
shortest_str = min(strs, key=len)
for i, char in enumerate(shortest_str):
for other in strs:
if other[i] != char:
return shortest_str[:i]
return shortest_str
strs = input("Enter the strings separated by space: ")
strs = strs.split()
print(longest_common_prefix(strs))

output:
3.Increement the last integer by 1 and return the resulting array of digits.
Program:
def myfun(r):
r[-1]+=1
return r
n=int(input("Enter the size:"))
print("Enter list elements:")
b=[]
for i in range(n):
a=int(input())
b.append(a)
print(myfun(b))

output:

4. Given an integer array nums,move all 0’s to the end of it while


maintaining the relative order of the non zero elements.
Program:
def myfun(num):
left=0
for right in range(len(num)):
if num[right]!=0:
num[left]=num[right]
left+=1
for i in range (left,len(num)):
num[i]=0
n=int(input("Enter number of elements:"))
a=[]
print("Enter the list elements:")
for I in range(n):
i=int(input())
a.append(i)
myfun(a)
print(a)

output:

5.Given an integer n, return true if it is a power of four otherwise return


false.
Program:
n=int(input("Enter a number:"))
def poweroffour(n):
if n<=0:
return False
while n%4==0:
n//=4
return n==1
print(poweroffour(n))
output:

6. Find the single element in a array that appears only once.


Program:
n=int(input("Enter the list size:"))
lst= []
print("Enter values :")
for i in range(0,n):
t=int(input())
lst.append(t)
#print(lst[i])
for i in range(0,n):
s=lst.count(lst[i])
if(s==1):
print("Single elements:",lst[i])
output:
7) Given a string word. A letter is called special if it appears both in
lowercase and uppercase in word.
Program:
def special_letters(word):
special = set()
for char in word:
if char.lower() != char.upper():
if char.lower() in word and char.upper() in word:
special.add(char.lower())
return special

word = input("Enter a word: ")


print(special_letters(word))
output:
8) Given an array of strings words, return the words that can be typed
using letters of the alphabet on only one row of American keyboard like the
image below.
Program:
def find_words(words):
keyboard_rows = [
set("qwertyuiop"),
set("asdfghjkl"),
set("zxcvbnm") ]
result = []
for word in words:
word_set = set(word.lower())
for row in keyboard_rows:
if word_set.issubset(row):
result.append(word)
break
return result
words = []
a=int(input("Enter no of strings:"))
print("enter strings:")
for i in range (0,a):
e=input()
words.append(e)
print(find_words(words)
output:
9. Given an integer num, repeatedly add all its digits until the result has only
one digit, and return it.
Program:
def add_digits(num):

while num >= 10:

num = sum(int(digit) for digit in str(num))

print(num)

return num

a=int(input("Enter a digit:"))

print("sum of digit until single digit obtain",add_digits(a))

output:

10) Given two binary strings a and b, return their sum as a binary string
Program:
def add_binary(a, b):
int_sum = int(a, 2) + int(b, 2)
binary_sum = bin(int_sum)[2:]
return binary_sum
a = input("Enter the first binary number: ")
b = input("Enter the second binary number: ")
print("Sum of the two binary numbers:", add_binary(a, b))
output:
11. Given an integer n, return true if it is a power of two. Otherwise, return
false.
Program:
def is_power_of_two(n):
if n <= 0:
return False
while n % 2 == 0:
n = n // 2
return n == 1
try:
num = int(input("Enter an integer: "))
result = is_power_of_two(num)
print(f"{num} is a power of two: {result}")
except ValueError:
print("Please enter a valid integer.")
output:
12.Return true if n is a happy number, and false if not.
Program:
def is_happy_number(n):
def get_next(number):
total_sum = 0
while number > 0:
digit = number % 10
total_sum += digit ** 2
number //= 10
return total_sum
seen_numbers = set()
while n != 1 and n not in seen_numbers:
seen_numbers.add(n)
n = get_next(n)
return n == 1
try:
num = int(input("Enter an integer: "))
result = is_happy_number(num)
print(f"{num} is a happy number: {result}")
except ValueError:
print("Please enter a valid integer.")
output:
13. check the number is perfect.
Program:
def is_perfect(n):
divisors = [i for i in range(1, n) if n % i == 0]
return sum(divisors) == n
#num = 28
num=int(input("enter a number"))
if is_perfect(num):
print(num," is a perfect number")
else:
print(num," is not a perfect number")

output:

14. You are climbing a staircase. It takes n steps to reach the top.Each time
you can either climb 1 or 2 steps. In how many distinct ways can you climb
to the top?
Program:
def climbStairs(n):
if n == 1:
return 1
if n == 2:
return 2
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
n = int(input("Enter the number of steps: "))
print("Number of distinct ways to climb to the top:", climbStairs(n))
output:

15.convert integer to the sum of two non zeros.


Program:
def nozero(n):
for a in range(10,n):
b=n-a
if '0' not in str(a) and '0' not in str(b):
return [a,b]
n=int(input("Enter the number"))
if n<=0:
print("Input must be a positive integer")
else:
result=nozero(n)
print("two no zero integers that add up to", n, "are:", result)
output:

16.Remove vowels from a string.


Program:
def remove(n):
vowels='aeiouAEUIOU'
result=""
for char in n:
if char not in vowels:
result +=char
return result
n=input("Enter the string:")
print("The Original String:",n)
print("String without vowels:",remove(n))

output:
17. Randomizer using a roll function
Program:
import random
number = random.randint(1, 6)
print(number )

output:

18.check the given string is palindrome or not.


Program:
st="javaJ"
strstr=st.casefold()
rev=reversed(strstr)
if list(strstr)==list(rev):
print("Palindrome")
else:
print("Not Palindrome")

output:
19. Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
Program:
import java.util.Scanner;
import java.util.Stack;
public class sol {
public boolean valid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false; }
char top = stack.pop();
if (c == ')' && top != '(') {
return false;
} else if (c == '}' && top != '{') {
return false;
} else if (c == ']' && top != '[') {
return false; }
}}
return stack.isEmpty();
}
public static void main(String[] args) {
sol solution = new sol();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a parentheses:");
String a = sc.nextLine();
if (a == null || a.trim().isEmpty()) {
System.out.println("Invalid input......");
} else {
System.out.println(solution.valid(a));
} }}
output:

20. Covert binary to integer


Program:
import java.util.Scanner;
public class so {
public static int convertBinaryArrayToInt(int[] binary) {
int result = 0;
int length = binary.length;
for (int i = 0; i < length; i++) {
result += binary[i] * Math.pow(2, length - 1 - i); }
return result;}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the length of the binary array: ");
int n = sc.nextInt();
int[] binary = new int[n];
System.out.println("Enter the binary array (separate elements by space): ");
for (int i = 0; i < n; i++) {
binary[i] = sc.nextInt(); }
int result = convertBinaryArrayToInt(binary);
System.out.println("Converted value: " + result); }}
output:

21. Given an array of integers nums and an integer target, return indices of
the two numbers such that they add up to target.
Program:
import java.util.*;

public class too {

public static int[] twoSum(int[] b, int target) {

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

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

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

return new int[] { i, j };

}} }

return new int[1]; }

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.print("Enter the number of elements in the array: ");

int n = s.nextInt();

int[] a= new int[n];

System.out.println("Enter the elements of the array:");


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

a[i] = s.nextInt();}

System.out.print("Enter the target sum: ");

int target = s.nextInt();

int[] result = twoSum(a, target);

if (result.length == 2) {

System.out.println("Indices of the two numbers: " + result[0] + ", " + result[1]); }

else {

System.out.println("No two numbers found that add up to the target.");

}}}

output:

22.check the given integer is palindrome or not.


Program:

class pal
{
public static void main(String args[]){
int x=12;
int reverse=0;
int temp=x;
while(temp != 0 ) {
int digit=temp%10;
reverse=reverse*10+digit;
temp/=10;
}
if(reverse==x)
System.out.println("x is palindrome");
else
System.out.println("x is not palindrome");}}

output:

23.Find two lines that together with the x-axis from a container,such that
the container contains the most water.Return the maximum amount of
water a container can store
Program:
h=[]
a=int(input("enter the array size:"))
for i in range (0,a):
b=int(input())
h.append(b)
print(h)
def max_area(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
width = right - left
current_height = min(height[left], height[right])
current_area = width * current_height
if current_area > max_area:
max_area = current_area
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
print(max_area(h))
output:

24. Given an integer, convert it to a Roman numeral.


Program:

import java.util.Scanner;
public class IntegerToRoman {
public static String intToRoman(int num) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V",
"IV", "I"};
StringBuilder roman = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (num >= values[i]) {
roman.append(symbols[i]);
num -= values[i];} }
return roman.toString(); }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("Roman numeral for " + number + " is " +
intToRoman(number));
scanner.close();}}

output:

25. Given two strings s and t, return true if t is an anagram of s, and false
otherwise.
Program:
def is_anagram(s, t):
return sorted(s) == sorted(t)
s = input("Please enter the first string: ")
t = input("Please enter the second string: ")
if is_anagram(s, t):
print("True")
else:
print("False")
output:
26.Write a function that takes in a string of one or more words, and returns
the same string, but with all words that have five or more letters reversed
(Just like the name of this Kata). Strings passed in will consist of only
letters and spaces. Spaces will be included only when more than one word
is present.
Program:
def reverse_long_words():
s= input("Please enter a sentence: ")
words = s.split()
reversed_words = []
for word in words:
if len(word) >= 5:
reversed_words.append(word[::-1])
else:
reversed_words.append(word)
print(" ".join(reversed_words))
reverse_long_words()
output:

27.Given a string s consisting of words and spaces, return the length of the
last word in the string.
Program:
def length_of_last_word(s: str) -> int:
words = s.strip().split()
if not words:
return 0
return len(words[-1])
input_string = "Hello World"
print(f"The length of the last word is: {length_of_last_word(input_string)}")
output:

28.Given a string and reverse only the string not other characters.
Program:
def reverse_letters(s):
s = list(s)
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalpha():
left += 1
elif not s[right].isalpha():
right -= 1
else:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
return ''.join(s)
st=input("enter the String:")
print(reverse_letters(st))
output:
29.Given integer find the digital root.

Program:
def digital_root(n):
if n==0:
return 0
return 1+(n-1)%9
n=int(input("enter a non negative integer:"))
print("digital root is:",digital_root(n))

output:

30.Find the position of the letter in alphabets.

Program:
def letter_to_position(s):
result=[]
for char in s:
if char.isalpha():
position=ord(char.lower())-ord('a')+1
result.append(str(position))
return ' '.join(result)
i=(input("enter the word:"))
print(letter_to_position(i))

output:
31.Find the given number odd or even using wired and not wired.
Program:
n=int(input("enter the number:"))
if(1<=n<=100):
if(n%2!=0):
print("wired")
elif(2<=n<=5)and(n%2==0):
print("not wired")
elif(6<=n<=20)and(n%2==0):
print("wired")
elif(n>20)and(n%2==0):
print("not wired")
else:
print("enter valid number")
output:

32.Sort elements of array without repetition.


Program:
a=[]
n=int(input("no of elements:"))
print("enter the elements:")
for m in range(n):
l=int(input())
a.append(l)
def st(a):
sa=sorted(a)
elements=[]
for i in sa:
if i not in elements:
elements.append(i)
return elements
def main():
res=st(a)
print("Sorted elements:",res)
main()
output:

33.Find all the sub string of the given string.


Program:
def substring (str):
r=1
for i in range (len (n)):
for j in range (i+1, len (n) +1):
print (n[i:j], end=" ")
r+=1
print ()
n=input("Enter the name: ")
substring (n)

output:
34.Merge two list and sort
Program:
l1=[]
l2=[]
num=int(input("num1:"))
for i in range (1, num+1):
b=int(input("element"))
l1. append (b)
num2=int(input ("num2: "))
for i in range (1,num2+1):
d=int(input("element"))
l2. append (d)
l3=l1+l2
l4=[]
l4=sorted(l3)
print("final", l4)

output:
35. Given an array that contains only 1 and 0 return the count of the
maximum consecutive ones in the array.
Program:
import java. util.*;
public class maximumcount {
public static int findMaxConsecutiveOnes(int nums[]) {
int cnt = 0;
int maxi = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
cnt++;
} else {
cnt = 0;}
maxi = Math.max(maxi, cnt);
} return maxi;}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n = scanner.nextInt();
int[]Array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++){
Array[i] = scanner.nextInt();}
int ans = findMaxConsecutiveOnes(Array);
System.out.println("The maximum consecutive 1's are " + ans);
}}
output:

36. find the peak value


Program:
def find_peak_element(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) //2
if nums[mid] < nums[mid + 1]:
left = mid + 1
else:
right = mid
return left
nums = [10, 20, 15, 25, 18, 22]
peak_index = find_peak_element(nums)
print(f"Peak element is at index: {peak_index}, value: {nums[peak_index]}")

output:

37.Given a string s and a dictionary of strings word Dict, return true if s


can be segmented into a space-separated sequence of one or more
dictionary words.

Program:
def wordBreak(s: str, wordDict: list[str]) -> bool:
word_set = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True # An empty string can always be segmented

for i in range(1, len(s) + 1):


for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break

return dp[len(s)]
s="samsung"
wordDict=["sam","sung"]
print(wordBreak(s,wordDict))

output:

38.Find the difference between given the two strings.


Program:
str1=input("Enter the elements")
str2=input("Enter the elements")
l1=list(str1)
l2=list(str2)
set1=set(l1)
set2=set(l2)
diff=set2-set1
print(diff)
output:
39.check the given no armstrong or not
Program:
def is_armstrong(n):
num_str = str(n)
num_digits = len(num_str)
sum = 0
for digit in num_str:
sum += int(digit) ** num_digits
return sum == n
num = int(input("Enter a number: "))
if is_armstrong(num):
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")

output:

40. Convert date format from "Day Month Year" (e.g., 12 Jan 2022) to
"DD-MM-YYYY".
Program:
def convert_date(date_str):
day,month,year=date_str.split()
day=day[:-2]#remove date('st','nd','rd','th')
month_map={"Jan":"1","Feb":"2","Mar":"3",
"Apr":"4","May":"5","Jun":"6",
"Jul":"7","Aug":"8","Sep":"9",
"Oct":"10","Nov":"11","Dec":"12"}
print (day,"-",month_map[month],"-",year)
#Read input from user
date_str=input("Enetr a date(Day Month Year): ")
#Call the functiton and print the result
(convert_date(date_str))

output:

You might also like