DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Assignment 2
Student Name: Shatakshi Rastogi UID: 22BCS14490
Branch: BE- CSE Date of Completion: 12-06-2024
Faculty Name: Ms. Shefali
Question 1
Aim: Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make a palindrome. A Palindrome String reads the same
backward as well as forward.
Objective: Minimum Insertion Steps to Make a String Palindrome.
Approach: The approach is defined below:
Reverse the strings.
Longest common subsequence.
Calculating minimum insertions.
Algorithm :
Initialisation.
Code:
Filling the DP(Dynamic Programming) table.
Compute result.
public class Solution {
public int minInsertions(String s)
{ int n = s.length();
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++)
{
dp[i][i] = 1;
}
for (int length = 2; length <= n; length++)
{ for (int i = 0; i <= n - length; i++)
{
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);}}} return n - dp[0][n - 1];
}
public static void main(String[] args) { Solution solution = new Solution(); String s1 = "pizzazz";
System.out.println(solution.minInsertions(s1)); // Output: 0 String s2 = "mbadm"; System.out.printl
}
}
Output:
Time complexity & Space Complexity: The algorithm uses a 2D array of size n to
store the lengths of the longest palindromic subsequences for all substrings of s. Therefore, the
space complexity is O(n^2).
The outer loop runs for all substring lengths from 2 to n, and the inner loop runs for all starting
indices i of those substrings. Therefore, the overall time complexity is O(n^2).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Question 2:
Aim: G i v e n a c o l l e c t i o n o f n u m b e r s , n u m s , t h a t m i g h t c o n t a i n
duplicates, return all possible unique permutations in any orde
r.Example 1:
Input nums: = [1,1,2]
Output: [[1,1,2], [1,2,1], [2,1,1]].
Objective: Permutations II.
Approach: Implement a method permuteUnique using backtracking to generate all unique
permutations of an integer array nums, sorting nums array to handle duplicates efficiently.
Use a boolean array used to track which elements have been used in each permutation, ensuring each
permutation is unique by skipping duplicates.
Algorithm:
Sort the array.
Initialize data structures.
Backtracking functions.
Generate permutations.
Return result.
Code: Through LEET CODE
import
java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> permuteUnique(int[] nums)
{ List<List<Integer>> result = new
ArrayList<>();
Arrays.sort(nums); // Sort to handle duplicates
backtrack(nums, new ArrayList<>(), new boolean[nums.length],
result); return result;
}
private void backtrack(int[] nums, List<Integer> tempList, boolean[]
used, List<List<Integer>> result) {
if (tempList.size() == nums.length) {
result.add(new
ArrayList<>(tempList)); return;
}
for (int i = 0; i < nums.length; i++) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
used[i] = true; tempList.add(nums[i]);
backtrack(nums, tempList, used, result); used[i] = false; tempList.remove(tempList.size() - 1);
}
}
}
public class __DriverSolution{
public static void main(String[] args) { int[] nums = {1, 1, 2};
List<List<Integer>> result = new Solution().permuteUnique(nums); System.out.println(result);
}
}
Output:
Time complexity & Space Complexity:
This complexity arises from generating n! permutations and each permutation involves
operations proportional to n due to array manipulation and sorting.
The time complexity is O(n * n!). Due to the recursive call stack, the space complexity is also the
same.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Question 3:
Aim: Given an array of strings strs, group the anagrams together. You can return the answer in
any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat", "tea", "tan", "ate","nat", "bat"]
Output: [["bat"],["nat", "tan"],["ate", "eat", "tea"]]
Objective: Group Anagrams.
Approach: To solve the problem of grouping anagrams from an array of strings (strs), we can
follow a systematic approach using a HashMap to categorize anagrams efficiently.
Algorithm:
Initialize a hash map.
Iterate through each string.
Collect results.
Time complexity & Space Complexity: Time complexity is O(n. k log k), where k is the
maximum length of string ‘strs’ and n is the number of strings ‘strs’.
Space complexity is O(n.k) for storing all the strings in a hash map.
Code: Through LEET CODE.
import
java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<List<String>> groupAnagrams(String[] strs)
{ Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String sortedStr = new String(charArray);
if (!map.containsKey(sortedStr)) {
map.put(sortedStr, new
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
map.get(sortedStr).add(s);
}
return new ArrayList<>(map.values());
}O
Output :
Question 4
Aim: Given an integer array nums and an integer k, return true if nums has a good subarray or
false otherwise.
A good subarray is a subarray where: its length is at least two,
and the sum of the elements of the subarray is a multiple of k.
Example 1:
Input: nums = [23,2,4,6,7], k =
6 Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
Objective: Continuous subarray sum.
Approach: Prefix sum and modulo approach is used.
Algorithm:
Initialize Data Structures.
Iterate through the array.
Compute modulo and handle negative Mod.
Check if the mod is in hashmap.
Store mod in hashmap.
Return false.
DEPARTMENT OF
COMPUTER SCIENCE &
Time complexity & Space Complexity: Time Complexity is O(n) where n is the
length of the array nums. We traverse the array once and perform constant time
operations for each element.
Space Complexity: O(min(n,k)), due to the usage of a HashMap that can store up
to min(n, k) unique mod values.
Code : Through Leet Code
import
java.util.HashMap;
Output:
import java.util.Map;
class Solution {
public boolean checkSubarraySum(int[] nums, int k)
{ int n = nums.length;
if (n < 2) return false;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1); // Initial prefix sum of 0 at index -1 (before start)
int sum = 0;
for (int i = 0; i < n; i++)
{ sum += nums[i];
int mod = sum % k;
if (mod < 0) mod += k; // Ensure mod is non-negative
if (map.containsKey(mod)) {
int prevIndex = map.get(mod);
if (i - prevIndex >= 2) return true;
} else {
map.put(mod,
i);}} return false;
DEPARTMENT OF
COMPUTER SCIENCE &
Question 5
Aim: G i v e n a n a r r a y o f s t r i n g s o f w o r d s r e p r e s e n t i n g a n E n g l i s
hDictionary, return the longest word in words that can be bui
ltone character at a time by other words in words.
If there is more than one possible answer, return the longes
tword with the smallest lexicographical order. If there is no
answer, return the empty string.
Note that the word should be built from left to right with eac
hadditional character being added to the end of a previous wor
d.E xamp l e 1:
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one
character at a time by "w", "wo", "wor", and "worl".
Objective: Longest word in the dictionary.
Approach: The approach is given below :
Sort the words.
Use a HashSet for efficiency.
Iterate through sorted words.
Check prefix existence.
Update the longest word.
Return result.
Algorithm:
Sort the input array words lexicographically.
Initialize an empty HashSet named built to store words that can be built from other words.
Initialize an empty string longest word to store the result.
Iterate through each word word in the sorted words array:
Check if the word is a single character or its prefix (substring from 0 to word. length() - 1)
exists inbuilt:
If true, add a word to built and update longestWord if the word is longer than longestWord.
Return the longest word as the result.
DEPARTMENT OF
COMPUTER SCIENCE &
Code: Through Leet Code
import
Output :
java.util.Arrays;
import
java.util.HashSet;
import java.util.Set;
class Solution {
public String longestWord(String[] words)
{ Arrays.sort(words);
Set<String> built = new
HashSet<>(); String longestWord =
"";
for (String word : words) {
if (word.length() == 1 || built.contains(word.substring(0, word.length() -
1))) {
built.add(word);
if (word.length() > longestWord.length())
{ longestWord = word;
}
}
}
DEPARTMENT OF
COMPUTER SCIENCE &
Time complexity & Space Complexity:
Time Complexity: O(n ⋅ m log m), where n is the number of words in the array of words and m is the
average length of the words. Sorting the array takes
O(n log n), and each word operation (insertion into HashSet and substring check) takes
O(m) on average.Space Complexity: O(n ⋅ m) due to the storage of words inbuilt and longest word.
THANK YOU, SHEFALI MAM.