Assignment Overview
In this assignment, you will solve 10 coding problems that test your understanding of array operations and string manipulation techniques. Each problem requires you to implement efficient algorithms using the concepts learned in Module 2.
Main.java file that demonstrates and tests all your solutions with sample inputs.
Arrays.sort() for sorting problems, or library pattern matching for string problems.
Array Operations (2.1)
Searching, sorting, two-pointer technique, and sliding window pattern
String Manipulation (2.2)
Pattern matching, palindromes, anagrams, and character frequency
Topics Covered
2.1 Array Operations & Techniques
- Array fundamentals and indexing - Traversal, manipulation, in-place operations
- Searching: Linear and binary search - Finding elements, search variants
- Sorting: Bubble, selection, insertion sort - Basic sorting algorithms
- Two-pointer technique and sliding window - Efficient array traversal patterns
2.2 String Manipulation
- String vs StringBuffer vs StringBuilder - Immutability, performance
- Pattern matching and KMP algorithm - Substring search
- Palindromes and anagrams - String comparison techniques
- Character frequency and substring problems - Counting, windowing
Part 1: Array Problems (75 Points)
Implement solutions for the following array problems. Each solution must include proper time and space complexity analysis in comments.
Binary Search Variants (15 points)
Create a class BinarySearchVariants.java with the following methods:
int firstOccurrence(int[] arr, int target)- Find the first occurrence of target in a sorted arrayint lastOccurrence(int[] arr, int target)- Find the last occurrence of target in a sorted arrayint countOccurrences(int[] arr, int target)- Count total occurrences using the above methodsint searchRotatedArray(int[] arr, int target)- Search in a rotated sorted array
// Example usage:
int[] arr = {1, 2, 2, 2, 3, 4, 5};
firstOccurrence(arr, 2); // Returns: 1
lastOccurrence(arr, 2); // Returns: 3
countOccurrences(arr, 2); // Returns: 3
int[] rotated = {4, 5, 6, 7, 0, 1, 2};
searchRotatedArray(rotated, 0); // Returns: 4
Sorting Algorithms (15 points)
Create a class SortingAlgorithms.java that implements:
void bubbleSort(int[] arr)- Bubble sort with optimization for already sorted arraysvoid selectionSort(int[] arr)- Selection sort implementationvoid insertionSort(int[] arr)- Insertion sort implementationvoid mergeSort(int[] arr, int left, int right)- Merge sort (divide and conquer)
For each algorithm, add a counter to track the number of comparisons and swaps made.
// Each method should print:
// "Bubble Sort: X comparisons, Y swaps"
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
// Output: Bubble Sort: 21 comparisons, 16 swaps
// Array: [11, 12, 22, 25, 34, 64, 90]
Two-Pointer Problems (15 points)
Create a class TwoPointerProblems.java with:
int[] twoSum(int[] arr, int target)- Find two numbers in a sorted array that sum to target. Return their indices.void reverseArray(int[] arr, int start, int end)- Reverse array in-place between indicesint removeDuplicates(int[] arr)- Remove duplicates from sorted array in-place, return new lengthvoid moveZeroes(int[] arr)- Move all zeroes to end while maintaining order of non-zero elements
// Example usage:
int[] arr1 = {2, 7, 11, 15};
twoSum(arr1, 9); // Returns: [0, 1] (arr1[0] + arr1[1] = 9)
int[] arr2 = {1, 1, 2, 2, 3};
removeDuplicates(arr2); // Returns: 3, arr2 becomes [1, 2, 3, ...]
int[] arr3 = {0, 1, 0, 3, 12};
moveZeroes(arr3); // arr3 becomes [1, 3, 12, 0, 0]
Sliding Window Problems (15 points)
Create a class SlidingWindowProblems.java with:
int maxSumSubarray(int[] arr, int k)- Find maximum sum of any contiguous subarray of size kint minSubarrayLength(int[] arr, int target)- Find minimum length subarray with sum ≥ targetint longestSubarrayWithKDistinct(int[] arr, int k)- Longest subarray with at most k distinct elements
// Example usage:
int[] arr1 = {2, 1, 5, 1, 3, 2};
maxSumSubarray(arr1, 3); // Returns: 9 (subarray [5, 1, 3])
int[] arr2 = {2, 3, 1, 2, 4, 3};
minSubarrayLength(arr2, 7); // Returns: 2 (subarray [4, 3])
int[] arr3 = {1, 2, 1, 2, 3};
longestSubarrayWithKDistinct(arr3, 2); // Returns: 4 ([1, 2, 1, 2])
Array Manipulation Challenge (15 points)
Create a class ArrayChallenge.java with:
int[] productExceptSelf(int[] nums)- Return array where each element is product of all other elements (without using division)int findMissingNumber(int[] arr, int n)- Find missing number in array containing 1 to n with one missingint majorityElement(int[] arr)- Find element appearing more than n/2 times (Boyer-Moore voting)int[][] mergeIntervals(int[][] intervals)- Merge overlapping intervals
// Example usage:
int[] arr1 = {1, 2, 3, 4};
productExceptSelf(arr1); // Returns: [24, 12, 8, 6]
int[] arr2 = {1, 2, 4, 5, 6};
findMissingNumber(arr2, 6); // Returns: 3
int[] arr3 = {3, 2, 3};
majorityElement(arr3); // Returns: 3
int[][] intervals = {{1,3}, {2,6}, {8,10}, {15,18}};
mergeIntervals(intervals); // Returns: {{1,6}, {8,10}, {15,18}}
Part 2: String Problems (75 Points)
Implement solutions for the following string manipulation problems. Focus on optimal time and space complexity.
String Basics (15 points)
Create a class StringBasics.java with:
String reverseString(String s)- Reverse a string without using StringBuilder.reverse()String reverseWords(String s)- Reverse order of words in a sentenceboolean isPalindrome(String s)- Check if string is palindrome (ignore non-alphanumeric, case-insensitive)String longestPalindromicSubstring(String s)- Find longest palindromic substring
// Example usage:
reverseString("hello"); // Returns: "olleh"
reverseWords("the sky is blue"); // Returns: "blue is sky the"
isPalindrome("A man, a plan, a canal: Panama"); // Returns: true
longestPalindromicSubstring("babad"); // Returns: "bab" or "aba"
Anagram Problems (15 points)
Create a class AnagramProblems.java with:
boolean isAnagram(String s1, String s2)- Check if two strings are anagramsList<List<String>> groupAnagrams(String[] strs)- Group anagrams togetherList<Integer> findAnagramIndices(String s, String p)- Find all start indices of p's anagrams in s
// Example usage:
isAnagram("anagram", "nagaram"); // Returns: true
isAnagram("rat", "car"); // Returns: false
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
groupAnagrams(strs);
// Returns: [["eat","tea","ate"], ["tan","nat"], ["bat"]]
findAnagramIndices("cbaebabacd", "abc");
// Returns: [0, 6] ("cba" at 0, "bac" at 6)
Pattern Matching (15 points)
Create a class PatternMatching.java with:
int naivePatternSearch(String text, String pattern)- Find first occurrence using brute force O(n*m)List<Integer> findAllOccurrences(String text, String pattern)- Find all occurrences of pattern in textint kmpSearch(String text, String pattern)- Implement KMP algorithm for pattern matchingint[] computeLPSArray(String pattern)- Helper method to compute LPS (Longest Proper Prefix Suffix) array for KMP
// Example usage:
naivePatternSearch("AABAACAADAABAAABAA", "AABA"); // Returns: 0
findAllOccurrences("AABAACAADAABAAABAA", "AABA"); // Returns: [0, 9, 13]
// KMP is more efficient for repeated searches
kmpSearch("ABABDABACDABABCABAB", "ABABCABAB"); // Returns: 10
computeLPSArray("ABABCABAB"); // Returns: [0, 0, 1, 2, 0, 1, 2, 3, 4]
Character Frequency Problems (15 points)
Create a class CharacterFrequency.java with:
char firstNonRepeatingChar(String s)- Find first non-repeating characterString removeDuplicates(String s)- Remove duplicate characters keeping first occurrenceboolean canFormPalindrome(String s)- Check if characters can be rearranged to form palindromeString frequencySort(String s)- Sort string by character frequency (most frequent first)
// Example usage:
firstNonRepeatingChar("leetcode"); // Returns: 'l'
firstNonRepeatingChar("aabb"); // Returns: '_' or '\0' (none found)
removeDuplicates("abracadabra"); // Returns: "abrcd"
canFormPalindrome("carrace"); // Returns: true ("racecar")
canFormPalindrome("hello"); // Returns: false
frequencySort("tree"); // Returns: "eert" or "eetr"
String Sliding Window (15 points)
Create a class StringSlidingWindow.java with:
int lengthOfLongestSubstring(String s)- Length of longest substring without repeating charactersString minWindow(String s, String t)- Minimum window in s containing all characters of tint characterReplacement(String s, int k)- Longest substring with same letters after at most k replacements
// Example usage:
lengthOfLongestSubstring("abcabcbb"); // Returns: 3 ("abc")
lengthOfLongestSubstring("bbbbb"); // Returns: 1 ("b")
lengthOfLongestSubstring("pwwkew"); // Returns: 3 ("wke")
minWindow("ADOBECODEBANC", "ABC"); // Returns: "BANC"
characterReplacement("AABABBA", 1); // Returns: 4 ("AABA" or "ABBA")
Submission
Create a public GitHub repository with the exact name shown below:
Required Repository Name
java-arrays-strings-dsa
Required Files
java-arrays-strings-dsa/
├── src/
│ ├── arrays/
│ │ ├── BinarySearchVariants.java # P1
│ │ ├── SortingAlgorithms.java # P2
│ │ ├── TwoPointerProblems.java # P3
│ │ ├── SlidingWindowProblems.java # P4
│ │ └── ArrayChallenge.java # P5
│ ├── strings/
│ │ ├── StringBasics.java # P6
│ │ ├── AnagramProblems.java # P7
│ │ ├── PatternMatching.java # P8
│ │ ├── CharacterFrequency.java # P9
│ │ └── StringSlidingWindow.java # P10
│ └── Main.java # Demo all solutions
├── test/
│ └── TestCases.java # Optional: JUnit tests
└── README.md # REQUIRED
README.md Must Include:
- Your full name and submission date
- Time and space complexity for each problem
- Brief explanation of your approach for challenging problems
- Instructions to compile and run (
javacandjavacommands)
Do Include
- All 10 problem solutions in separate files
- Main.java demonstrating each solution
- Time/space complexity comments in code
- Edge case handling (empty arrays, single elements)
- Clean, readable code with proper naming
- README with complexity analysis
Do Not Include
- Built-in Arrays.sort() for sorting problems
- Library pattern matching (regex for P8)
- Any .class files (compiled bytecode)
- IDE-specific folders (.idea, .vscode)
- Solutions copied from online sources
- Code that doesn't compile
javac src/**/*.java.
Enter your GitHub username - we'll verify your repository automatically
Grading Rubric
Your assignment will be graded on the following criteria:
| Problem | Points | Key Criteria |
|---|---|---|
| P1: Binary Search Variants | 15 | O(log n) complexity, handles edge cases, rotated array works |
| P2: Sorting Algorithms | 15 | Correct implementations, comparison/swap counters, stable where needed |
| P3: Two-Pointer Problems | 15 | O(n) complexity, in-place operations, correct indices |
| P4: Sliding Window | 15 | Optimal O(n) solutions, correct window management |
| P5: Array Challenge | 15 | No division for P5a, Boyer-Moore for P5c, interval merging logic |
| P6: String Basics | 15 | Efficient reversal, proper palindrome handling |
| P7: Anagram Problems | 15 | O(n) anagram check, correct grouping, sliding window for indices |
| P8: Pattern Matching | 15 | Correct KMP implementation, LPS array computation |
| P9: Character Frequency | 15 | Efficient frequency counting, correct palindrome logic |
| P10: String Sliding Window | 15 | Optimal solutions, correct minimum window |
| Total | 150 |
Ready to Submit?
Make sure you have completed all 10 problems and reviewed the grading rubric above.
Submit Your AssignmentWhat You Will Practice
Searching Algorithms
Binary search variants, rotated array search, and pattern matching techniques
Sorting Algorithms
Bubble, selection, insertion, and merge sort with performance analysis
Two-Pointer Technique
Efficient array traversal for pair finding, reversal, and duplicate removal
Sliding Window Pattern
Fixed and variable size windows for subarray and substring problems
Pro Tips
Array Tips
- For binary search, always check mid calculation to avoid overflow
- Two-pointer works best on sorted arrays
- Sliding window: expand right, shrink left as needed
- In-place operations save space but modify original
String Tips
- Use char[] for in-place string manipulation
- HashMap for O(1) character frequency lookup
- StringBuilder for efficient concatenation
- ASCII values: 'a' = 97, 'A' = 65, '0' = 48
Complexity Tips
- Binary search = O(log n), use when sorted
- Two-pointer on sorted = O(n)
- Sliding window = O(n) for subarray/substring
- HashMap lookup = O(1) average
Common Pitfalls
- Off-by-one errors in binary search bounds
- Forgetting to handle empty array/string
- String immutability in Java
- Integer overflow in mid calculation