Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Sno 717

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Assignment 2

Student Name: Harender Singh UID: 22BCS11997


Branch: BE- CSE Date of Completion: 14/06/2024
Faculty Name: Ms. Jyoti

Question 1: Minimum Insertion Steps to Make a String Palindrome - LeetCode

Aim: To determine the minimum number of insertions required to transform a given


string s into a palindrome.

Objective: The objective is to find the minimum number of steps to make the string s
a palindrome by inserting characters at any position.

Approach: The approach is based on dynamic programming. The key idea is to find
the longest palindromic subsequence (LPS) in the string s. The minimum number of
insertions required is the difference between the length of the string s and the length
of the LPS.

Algorithm:

1. Initialize:

 Let n be the length of the string s.


 Initialize a 2D array dp of size (n x n) where dp[i][j] represents the minimum
number of insertions required to make the substring s[i:j+1] a palindrome.

2. Base Case:

 Initialize dp[i][i] = 0 for all i (single character substrings are already


palindromes).

3. Fill the DP Table:

 Iterate over all possible lengths of substrings l from 2 to n.


 For each substring of length l starting from index i:

o Calculate the end index j = i + l - 1.


o If s[i] == s[j], then dp[i][j] = dp[i+1][j-1].
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

4. Result:

 The minimum number of insertions required to make the entire string s a


palindrome is stored in dp[0][n-1].

Code:

class Solution:
def minInsertions(self, s: str) -> int:
n = len(s)
dp = [[0] * n for _ in range(n)]

for i in range(n):
dp[i][i] = 1

for i in range(n - 2, -1, -1):


for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = 2 + dp[i + 1][j - 1]
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

return n - dp[0][n - 1]

Output:

Time complexity: O(n^2) where n is the length of the string s.

Space Complexity: O(n^2) due to the DP table.


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Question 2: Permutations II - LeetCode


Aim: Generate all unique permutations of a collection of numbers nums that may
contain duplicates.

Objective: To produce a list of all unique permutations of nums in any order.

Approach: Use a Depth-First Search (DFS) approach with backtracking to generate


permutations while ensuring uniqueness.

Algorithm:

1. Sort the Input:

 Sort nums to bring duplicates together. This allows us to handle duplicates by


only including a number if it hasn't been used yet in the current permutation.

2. DFS with Backtracking:

 Use recursion (DFS) to explore all possible permutations.


 Maintain a boolean array used to track which numbers have been used in the
current permutation to avoid duplicates.
 For each position in the permutation:

o Skip duplicates to ensure uniqueness.


o Add the current number to the permutation.
o Recursively generate permutations for the remaining numbers.
o Backtrack by removing the number from the permutation and marking it
as unused.

3. Store Unique Permutations:

• Use a set to store unique permutations to avoid duplicates in the result.

4. Convert Set to List:

• Convert the set of unique permutations to a list before returning.


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Code:

class Solution:
def __init__(self):
self.res = []

def permute(self, nums, start):


if start == len(nums):
self.res.append(nums[:])
return
for i in range(start, len(nums)):
if i == start or nums[start] != nums[i]:
nums[start], nums[i] = nums[i], nums[start]
self.permute(nums[:], start + 1)
def permuteUnique(self, nums):
nums.sort()
self.permute(nums, 0)
return self.res

Output:

Time complexity: O(n*n!)

Space Complexity: O(n*n!)


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Question 3: Group Anagrams - LeetCode

Aim: Group the anagrams from the array strs together.

Objective: Return a list of groups where each group contains strings that are
anagrams of each other.

Approach: Use a hash map to efficiently group anagrams based on their sorted
character representation.

Algorithm:

1. Initialize a Hash Map:

 Use a hash map (dict in Python) where the key is the sorted version of each
string (sorted characters), and the value is a list of strings that match this sorted
key.

2. Group Anagrams:

 Iterate through each string in strs.


 Sort the characters of the string to get its canonical form (sorted key).
 Add the string to the list corresponding to its sorted key in the hash map.

3. Return the Result:

 Convert the values of the hash map (lists of anagrams) into a list and return it.

Code:

from collections import defaultdict

class Solution:
def groupAnagrams(self, strs):
mp = defaultdict(list)

for x in strs:
word = ''.join(sorted(x))
mp[word].append(x)

return list(mp.values())
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output:

Time complexity: O(n * k log k)

Space Complexity: O(n * k)


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Question 4: Continuous Subarray Sum - LeetCode


Aim: To determine if there exists a contiguous subarray in nums where the sum of its
elements is a multiple of k and the length of the subarray is at least two.

Objective: Return true if such a subarray exists, otherwise return false.

Approach: Use a hash map to keep track of cumulative sums modulo k encountered
so far. If we encounter the same cumulative sum modulo k again, it implies that the
subarray between these two indices has a sum that is a multiple of k.

Algorithm:

1. Initialize Variables:

 Use a hash map mod_k to store cumulative sums modulo k and their
corresponding indices.
 Initialize prefix to 0 to track the cumulative sum as we iterate through nums.
 Initialize mod_k[0] = -1 to handle cases where the entire prefix sum up to the
current index is a multiple of k.

2. Iterate through nums:

 Compute the prefix sum by adding each element of nums.


 Compute prefix % k to get the current remainder when divided by k.
 If mod_k already contains this remainder, check if the difference in indices
between the current index and the stored index in mod_k is at least 2. If yes,
return true.
 Otherwise, store the current remainder and its index in mod_k.

3. Return Result:

 If no valid subarray is found during the iteration, return false.


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Code:

class Solution:
@staticmethod
def checkSubarraySum(nums, k):
n = len(nums)
if n < 2:
return False

mod_k = {}
prefix = 0
mod_k[0] = -1

for i in range(n):
prefix += nums[i]
prefix %= k
if prefix in mod_k:
if i > mod_k[prefix] + 1:
return True
else:
mod_k[prefix] = i

return False

Output:

Time complexity: O(n)

Space Complexity: O(min(n,k))


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Question 5: Longest Word in Dictionary - LeetCode

Aim: Find the longest word in the array words that can be formed by concatenating
other words from the same array, character by character from left to right.

Objective: Return the longest word with the smallest lexicographical order if there
are multiple candidates, or an empty string if no such word exists.

Approach: Use a set (built) to keep track of words that can be constructed so far, and
iterate through words to check if each word can be formed by appending characters to
previously formed words.

Algorithm:

1. Sort the Input:

 Sort words lexicographically to prioritize checking shorter words first, as


longer words must be built from shorter ones.

2. Iterate and Build Words:

 Initialize an empty set built to store words that can be constructed.


 Iterate through each word in the sorted words:

o Check if the prefix (all characters except the last one) of the current word
exists in built.
o If yes, add the current word to built.

3. Track Longest Word:

 As you iterate through words, update the longest_word variable whenever you
find a longer word that can be built.

4. Return Result:

 Return the longest_word found, which is the longest word that can be built
from other words in words.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Code:

class Solution:
def longestWord(self, words):
words.sort()
built = set()
res = ""

for w in words:
if len(w) == 1 or w[:-1] in built:
if len(w) > len(res):
res = w
built.add(w)

return res

Output:

Time complexity: O(nlogn)


Space Complexity: O(n)

You might also like