Assignment 2-A

Array & String Problems

Solve 10 coding problems covering array operations, searching algorithms, sorting techniques, two-pointer and sliding window patterns, and string manipulation challenges. Each problem tests your understanding of fundamental DSA concepts.

4-6 hours
Intermediate
150 Points
Submit Assignment
What You'll Practice
  • Binary search implementation
  • Sorting algorithm coding
  • Two-pointer technique
  • Sliding window pattern
  • String pattern matching
Contents
01

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.

Format: Create a Java project with separate classes for each problem. Include a Main.java file that demonstrates and tests all your solutions with sample inputs.
Important: You must implement the algorithms yourself. Do NOT use built-in sorting methods like Arrays.sort() for sorting problems, or library pattern matching for string problems.
Skills Applied: This assignment tests your understanding of Array Operations & Techniques (Topic 2.1) and String Manipulation (Topic 2.2) from Module 2.
Array Operations (2.1)

Searching, sorting, two-pointer technique, and sliding window pattern

String Manipulation (2.2)

Pattern matching, palindromes, anagrams, and character frequency

Ready to submit? Already completed the assignment? Submit your work now!
Submit Now
02

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
03

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.

P1
Binary Search Variants (15 points)

Create a class BinarySearchVariants.java with the following methods:

  1. int firstOccurrence(int[] arr, int target) - Find the first occurrence of target in a sorted array
  2. int lastOccurrence(int[] arr, int target) - Find the last occurrence of target in a sorted array
  3. int countOccurrences(int[] arr, int target) - Count total occurrences using the above methods
  4. int 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
P2
Sorting Algorithms (15 points)

Create a class SortingAlgorithms.java that implements:

  1. void bubbleSort(int[] arr) - Bubble sort with optimization for already sorted arrays
  2. void selectionSort(int[] arr) - Selection sort implementation
  3. void insertionSort(int[] arr) - Insertion sort implementation
  4. void 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]
P3
Two-Pointer Problems (15 points)

Create a class TwoPointerProblems.java with:

  1. int[] twoSum(int[] arr, int target) - Find two numbers in a sorted array that sum to target. Return their indices.
  2. void reverseArray(int[] arr, int start, int end) - Reverse array in-place between indices
  3. int removeDuplicates(int[] arr) - Remove duplicates from sorted array in-place, return new length
  4. void 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]
P4
Sliding Window Problems (15 points)

Create a class SlidingWindowProblems.java with:

  1. int maxSumSubarray(int[] arr, int k) - Find maximum sum of any contiguous subarray of size k
  2. int minSubarrayLength(int[] arr, int target) - Find minimum length subarray with sum ≥ target
  3. int 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])
P5
Array Manipulation Challenge (15 points)

Create a class ArrayChallenge.java with:

  1. int[] productExceptSelf(int[] nums) - Return array where each element is product of all other elements (without using division)
  2. int findMissingNumber(int[] arr, int n) - Find missing number in array containing 1 to n with one missing
  3. int majorityElement(int[] arr) - Find element appearing more than n/2 times (Boyer-Moore voting)
  4. 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}}
04

Part 2: String Problems (75 Points)

Implement solutions for the following string manipulation problems. Focus on optimal time and space complexity.

P6
String Basics (15 points)

Create a class StringBasics.java with:

  1. String reverseString(String s) - Reverse a string without using StringBuilder.reverse()
  2. String reverseWords(String s) - Reverse order of words in a sentence
  3. boolean isPalindrome(String s) - Check if string is palindrome (ignore non-alphanumeric, case-insensitive)
  4. 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"
P7
Anagram Problems (15 points)

Create a class AnagramProblems.java with:

  1. boolean isAnagram(String s1, String s2) - Check if two strings are anagrams
  2. List<List<String>> groupAnagrams(String[] strs) - Group anagrams together
  3. List<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)
P8
Pattern Matching (15 points)

Create a class PatternMatching.java with:

  1. int naivePatternSearch(String text, String pattern) - Find first occurrence using brute force O(n*m)
  2. List<Integer> findAllOccurrences(String text, String pattern) - Find all occurrences of pattern in text
  3. int kmpSearch(String text, String pattern) - Implement KMP algorithm for pattern matching
  4. int[] 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]
P9
Character Frequency Problems (15 points)

Create a class CharacterFrequency.java with:

  1. char firstNonRepeatingChar(String s) - Find first non-repeating character
  2. String removeDuplicates(String s) - Remove duplicate characters keeping first occurrence
  3. boolean canFormPalindrome(String s) - Check if characters can be rearranged to form palindrome
  4. String 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"
P10
String Sliding Window (15 points)

Create a class StringSlidingWindow.java with:

  1. int lengthOfLongestSubstring(String s) - Length of longest substring without repeating characters
  2. String minWindow(String s, String t) - Minimum window in s containing all characters of t
  3. int 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")
05

Submission

Create a public GitHub repository with the exact name shown below:

Required Repository Name
java-arrays-strings-dsa
github.com/<your-username>/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 (javac and java commands)
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
Important: Test all your solutions with edge cases (empty inputs, single elements, duplicates) before submitting. Make sure your code compiles with javac src/**/*.java.
Submit Your Assignment

Enter your GitHub username - we'll verify your repository automatically

06

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 Assignment
07

What 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

08

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
09

Pre-Submission Checklist

Part 1: Arrays
Part 2: Strings
Repository Checklist