DSA Series — Day 1 : Problem 3 | Arrays Problem: Check if Array Is Sorted and Rotated 🔹 Problem Understanding: An array is considered sorted and rotated if it was originally sorted in non-decreasing order and then rotated some number of times (including zero). 🔹 Approach: Traverse the array and track the number of times the order decreases (a “dip”). A valid sorted & rotated array can have at most one dip. After the dip, ensure remaining elements do not violate the circular sorted order by comparing with the first element. 🔹 Why this works: A sorted array rotated once will show exactly one break in order. More than one break means the array cannot be derived from a sorted sequence. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: ( Text / Image ) class Solution { public boolean check(int[] nums) { boolean dipAllow = true; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { if (dipAllow) dipAllow = false; else return false; } if (!dipAllow && (nums[i] > nums[0] || nums[nums.length - 1] > nums[0])) { return false; } } return true; } } 🔹 Key Insight: The core idea is limiting the array to only one order violation. Anything beyond that breaks the definition of sorted rotation. 📈 Continuing my daily DSA problem-solving series. #DSA #Arrays #Java #ProblemSolving #StriversA2Z #CodingJourney
Check if Array is Sorted and Rotated in Java
More Relevant Posts
-
📌 DSA Series — Day 4 | Problem 1 | Arrays Problem: Longest Subarray with Given Sum K (Positive Integers) 🔹 Problem Understanding: Given an array of positive integers and an integer K, find the length of the longest subarray whose sum is exactly K. 🔹 Approach (Sliding Window): Use two pointers (left and right) to represent a window. Expand the window by moving right and adding elements to the sum. Shrink the window from the left whenever the sum exceeds K. Update the maximum length when the window sum equals K. 🔹 Why this works: Since all elements are positive, increasing the window always increases the sum and shrinking it always decreases the sum. This monotonic behavior makes the sliding window approach valid and optimal. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: class Solution { public int longestSubarray(int[] arr, int k) { int left = 0, sum = 0, maxLen = 0; for (int right = 0; right < arr.length; right++) { sum += arr[right]; while (sum > k) { sum -= arr[left++]; } if (sum == k) { maxLen = Math.max(maxLen, right - left + 1); } } return maxLen; } } 🔹 Key Insight: This approach fails when negative numbers are present. 📈 Continuing my structured DSA problem-solving series. #DSA #Arrays #Java #SlidingWindow #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
📌 DSA Series — Day 3 | Arrays (Problem 1) Problem: Union of Two Arrays (with Duplicates) 🔹 Problem Understanding: Given two arrays, find the union of both arrays such that the result contains only unique elements, even if duplicates exist in the input arrays. 🔹 Approach (HashSet-based): Use a HashSet to automatically handle duplicates. Insert all elements from both arrays into the set. Convert the set to a list and sort it to return the union in ascending order. 🔹 Why this works: A Set guarantees uniqueness, which removes duplicates efficiently without manual checks. 🔹 Time Complexity: Insertion into HashSet: O(n + m) Sorting the result: O(k log k) (where k is the number of unique elements) 🔹 Space Complexity: O(n + m) 🔹 Java Implementation: class Solution { public static ArrayList<Integer> findUnion(int[] a, int[] b) { Set<Integer> lst = new HashSet<>(); for (Integer item : a) { lst.add(item); } for (Integer item : b) { lst.add(item); } ArrayList<Integer> response = new ArrayList<>(lst); Collections.sort(response); return response; } } 🔹 Key Insight: Using a HashSet simplifies the problem, but if both arrays are already sorted, a two-pointer approach can achieve the same result with O(1) extra space. 📈 Continuing my structured DSA problem-solving series. #DSA #Arrays #Java #HashSet #ProblemSolving #StriversA2Z #CodingJourney #GFG #LeetCode
To view or add a comment, sign in
-
-
📌 DSA Series — Day 2 - Problem 2 | Arrays Problem: Rotate Array (Rotate Right by k Steps) 🔹 Problem Understanding: Given an array, rotate it to the right by k steps, where k can be greater than the array length. 🔹 Approach: Reduce k using modulo (k % n) to avoid unnecessary rotations. Store the last k elements in a temporary array. Shift the remaining elements to the right by k positions. Copy the stored elements back to the front. 🔹 Why this works: Right rotation essentially moves the last k elements to the front while preserving the order of the rest. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(k) 🔹 Java Implementation: class Solution { public void rotate(int[] nums, int k) { if (nums == null || nums.length == 0) return; k %= nums.length; if (k == 0) return; // Createing a Temp array int n = nums.length; int[] temp = new int[k]; // Copy last k elements for (int i = 0; i < k; i++) { temp[i] = nums[n - k + i]; } // Shift remaining elements for (int i = n - 1; i >= k; i--) { nums[i] = nums[i - k]; } // Restore temp for (int i = 0; i < k; i++) { nums[i] = temp[i]; } } } 🔹 Key Insight: Using modulo prevents redundant rotations when k is larger than the array size. 📈 Continuing my daily DSA problem-solving series. #DSA #Arrays #Java #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
While solving DSA problems recently, I encountered a small yet significant detail in Java that can lead to incorrect answers and silent bugs. I was comparing two strings like this: String s1 = new String("abbc"); String s2 = new String("abbc"); At first glance, it seems obvious that both strings are identical. However, when I checked: s1 == s2 // false This result surprised me. The reason is that in Java, the "==" operator does not compare the actual string values; it compares memory references. Even though both strings contain "abbc," they are two different objects created in memory. What actually works is: s1.equals(s2) // true The .equals() method compares the content inside the objects, which is typically what we want when working with Strings. This can become even more confusing with string literals: String a = "DSA"; String b = "DSA"; a == b // true In this case, Java uses the String Constant Pool, so both variables point to the same object. This can make == appear to work, but relying on it is risky and inconsistent. Key takeaways from this: - "==" checks reference equality, not value - .equals() checks actual string content - String Pool optimizations can hide bugs - One wrong operator can disrupt DSA logic, HashMaps, or real-world code DSA isn’t just about algorithms; it compels you to understand how the language behaves under the hood, truly. Have you ever lost time debugging something that came down to a single operator? #Java #DSA #Programming #SoftwareEngineering #JVM #CleanCode #CodingInterviews #BackendDevelopment #ProblemSolving
To view or add a comment, sign in
-
📌 DSA Series — Day 2 : Problem 1 | Arrays Problem: Remove Duplicates from Sorted Array 🔹 Approach (Two-Pointer Technique): Maintain a pointer (firstPtr) that tracks the position of the last unique element. Traverse the array and overwrite duplicates by shifting only unique elements forward. Since the array is sorted, duplicates always appear consecutively. 🔹 Why this works: Sorted order guarantees that a change in value indicates a new unique element. This allows in-place modification without using extra memory. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: class Solution { public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int firstPtr = 0; for (int item : nums) { if (nums[firstPtr] != item) { nums[++firstPtr] = item; } } // +1 converts index to count of unique elements return firstPtr + 1; } } 🔹 Key Insight: The trick is realizing that the problem cares about the count of unique elements, not the remaining values beyond that count. 📈 Continuing my daily DSA problem-solving series. #DSA #Arrays #Java #TwoPointers #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
Day 11 ( DSA using Java) To strengthen my foundation in Data Structures and Algorithms, I’m committing to solving and sharing LeetCode problem in regular periods of time, along with my thought process and approach. Writing it out helps me learn better and opens the door to meaningful discussion. 🔹 Problem: Q1662 > check if two String Arrays are equivalent 🔹 Core Concept: String , String Functions. solution : public class StringLC { public static boolean arrayStringsAreEqual(String[] word1, String[] word2) { if(String.join("",word1).equals(String.join("",word2))){ return true; } return false; } public static void main(String[] args) { String[] word1 = {"ab","c"}; String[] word2 = {"a","bc"}; System.out.println(arrayStringsAreEqual(word1, word2)); } } I’ve included my solution and time–space complexity analysis. I’d love to hear how others approached this problem—were there alternative or more efficient strategies? Let’s learn, improve, and grow together. #LeetCode #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #LearningInPublic #Java
To view or add a comment, sign in
-
Learned something interesting about the char data type in Java today. I used to think char only stores characters. Turns out its numeric underneath. This small snippet made it obvious: char ch = 'A'; System.out.println(ch); // output: A System.out.println(ch + 1); // output: 66 'A' isn’t just a character, it has a numeric value (65). When Java performs arithmetic, it treats char as an integer. Tried this as well: char ch = '8'; System.out.println(ch); // output: 8 System.out.println((int) ch); // output: 56 That’s when ASCII / Unicode actually made sense instead of feeling like theory. Still learning the basics but understanding what’s happening underneath makes a big difference. #Java #LearningInPublic #Beginner #DSA
To view or add a comment, sign in
-
📌 DSA Problem Series – Day 15 | Problem 2 | Array 🔹 Problem: Missing and Repeating Number 🧠 Problem Statement: You are given an array of size N containing numbers from 1 to N. One number is missing One number is repeating Your task is to find both numbers. ✅ Approach Used Use a HashMap to track frequency of elements Identify the repeating number when frequency > 1 Use mathematical sum formula to compute the missing number 💻 Java Solution class Solution { ArrayList<Integer> findTwoElement(int arr[]) { Map<Integer, Integer> map = new HashMap<>(); int n = arr.length; int expectedSum = n * (n + 1) / 2; int repeatingNumber = -1; int actualSum = 0; for (int item : arr) { if (map.containsKey(item)) { repeatingNumber = item; } map.put(item, map.getOrDefault(item, 0) + 1); actualSum += item; } int missingNumber = expectedSum - (actualSum - repeatingNumber); return new ArrayList<>(Arrays.asList(repeatingNumber, missingNumber)); } } ⏱️ Complexity Time Complexity: O(N) Space Complexity: O(N) 🎯 Key Takeaway Combining hashing with basic mathematics makes this problem simple and efficient. This pattern appears frequently in interviews and competitive programming. #DSA #Java #ProblemSolving #Arrays #CodingInterview #LeetCode #HashMap #Backend
To view or add a comment, sign in
-
-
📌 DSA Series — Day 2 : Problem 3| Arrays Problem: Move Zeroes 🔹 Problem Understanding: Given an array, move all 0s to the end while maintaining the relative order of non-zero elements. The operation must be done in-place. 🔹 Approach: Use a pointer to track the position where the next non-zero element should be placed. Traverse the array and copy all non-zero elements forward. After that, fill the remaining positions with 0. 🔹 Why this works: The relative order of non-zero elements is preserved, and all zeroes are pushed to the end without extra data structures. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(1) 🔹 Java Implementation: class Solution { public void moveZeroes(int[] nums) { int temp = 0; for (int item : nums) { if (item != 0) { nums[temp++] = item; } } while (temp < nums.length) { nums[temp++] = 0; } } } 🔹 Key Insight: This is a classic two-pointer overwrite technique—simple, efficient, and commonly asked in interviews. 📈 Continuing my structured DSA problem-solving series. #DSA #Arrays #Java #TwoPointers #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
Java forces you to be explicit about 𝐡𝐨𝐰 𝐝𝐚𝐭𝐚 𝐥𝐢𝐯𝐞𝐬 𝐢𝐧 𝐦𝐞𝐦𝐨𝐫𝐲. That’s why primitive types exist. When you use primitives like 𝗶𝗻𝘁, 𝗱𝗼𝘂𝗯𝗹𝗲, or 𝗯𝗼𝗼𝗹𝗲𝗮𝗻, you’re working directly with values — not objects, not references. This matters more than it looks. Primitive types: • Are faster to access • Use less memory • Behave predictably Compare that with objects. Objects live on the heap, come with overhead, and are accessed through references. Early on, this difference feels theoretical. Later, it explains performance issues, memory leaks, and why certain designs don’t scale. Understanding primitives teaches an important habit: 𝗰𝗵𝗼𝗼𝘀𝗲 𝘁𝗵𝗲 𝘀𝗶𝗺𝗽𝗹𝗲𝘀𝘁 𝗿𝗲𝗽𝗿𝗲𝘀𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻 𝘁𝗵𝗮𝘁 𝘀𝗼𝗹𝘃𝗲𝘀 𝘁𝗵𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺. Not everything needs to be an object. Not everything needs abstraction. Today was about: • What primitive data types really are • How they differ from reference types • Why memory awareness matters in Java Good performance doesn’t start with optimization. It starts with understanding fundamentals. #Java #Performance #MemoryManagement #Programming #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development