🚀 Day 1 of My Coding Challenge Today I solved an interesting problem on Array Rotation using Java. 🔹 Problem: Rotate an array to the left by ‘d’ positions efficiently. 🔹 Approach: Instead of shifting elements one by one, I used the Reversal Algorithm: 1️⃣ Reverse first d elements 2️⃣ Reverse remaining elements 3️⃣ Reverse entire array 🔹 Example: Input: [1, 2, 3, 4, 5], d = 2 Output: [3, 4, 5, 1, 2] 🔹 What I learned: ✔ Optimized solution from O(n*d) → O(n) ✔ Importance of breaking problems into smaller steps ✔ In-place array manipulation 💻 Code: ```java import java.util.Arrays; class Solution { public static int[] reverse(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr; } static int[] rotateArr(int arr[], int d) { int n = arr.length; d = d % n; if (d < 0) { d = d + n; } reverse(arr, 0, d - 1); reverse(arr, d, n - 1); reverse(arr, 0, n - 1); return arr; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int d = 2; int[] res = rotateArr(arr, d); System.out.println(Arrays.toString(res)); } } ``` #Java #DSA #CodingChallenge #50DaysOfCode #LearningJourney #PlacementPreparation
Optimized Array Rotation in Java with Reversal Algorithm
More Relevant Posts
-
Day 11/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Compile-time vs Runtime Polymorphism 💻 Practice Code: 🔸 Compile-time Polymorphism (Method Overloading) class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 🔸 Runtime Polymorphism (Method Overriding) class Animal { void sound() { System.out.println("Animal sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { // Compile-time Calculator c = new Calculator(); System.out.println(c.add(10, 20)); System.out.println(c.add(10, 20, 30)); // Runtime Animal a = new Cat(); a.sound(); } } 📌 Key Learnings: ✔️ Compile-time → method decided at compile time ✔️ Runtime → method decided at runtime ✔️ Overloading vs Overriding difference 🎯 Focus: Understanding how Java resolves method calls 🔥 Interview Insight: Difference between compile-time and runtime polymorphism is one of the most frequently asked Java interview questions. #Java #100DaysOfCode #MethodOverloading #MethodOverriding #Polymorphism #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
Leetcode Practice - 15. 3Sum The problem is solved using JAVA. Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
--->> Understanding Inheritance in Java & Its Types **Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows one class to acquire the properties and behaviors of another class. √ What is Inheritance? It is the process where a child class inherits variables and methods from a parent class using the extends keyword. ~Why is it Important? ✔️ Code reusability ✔️ Reduced development time ✔️ Better maintainability ✔️ Cleaner and scalable design @ Types of Inheritance in Java 1️⃣ Single Inheritance 2️⃣ Multilevel Inheritance 3️⃣ Hierarchical Inheritance 4️⃣ Hybrid (combination of types) # Important Notes 🔸 Java does NOT support multiple inheritance using classes ➡️ Because of the Diamond Problem (ambiguity in method resolution) 🔸 Cyclic inheritance is not allowed ➡️ Prevents infinite loops in class relationships 💻 Code Example (Single Inheritance) Java class Parent { void show() { System.out.println("This is Parent class"); } } class Child extends Parent { void display() { System.out.println("This is Child class"); } } public class Main { public static void main(String[] args) { Child obj = new Child(); obj.show(); // inherited method obj.display(); // child method } } 👉 Here, the Child class inherits the show() method from the Parent class. -->> Real-World Example Think of a Vehicle system 🚗 Parent: Vehicle Child: Car, Bike All vehicles share common features like speed and fuel, but each has its own unique behavior. @ Key Takeaway Inheritance helps you avoid code duplication and build efficient, reusable, and scalable application TAP Academy #Java #OOP #Inheritance #Programming #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava
To view or add a comment, sign in
-
-
Day 53 of Sharing What I’ve Learned 🚀 ArrayDeque in Java — Fast & Flexible Queue Alternative After understanding how LinkedList works as a Queue, I explored a more optimized and powerful structure in the Java Collections Framework — ArrayDeque 🔹 What is ArrayDeque? ArrayDeque is a resizable array-based implementation of a Deque (Double-Ended Queue). 👉 It allows insertion and deletion from both ends efficiently. 🔹 Why use ArrayDeque over LinkedList? ✔ Faster Performance No node traversal → better speed compared to LinkedList. ✔ No Extra Memory Overhead Doesn’t store pointers like LinkedList → more memory efficient. ✔ Better Cache Performance Elements are stored contiguously → faster access. ✔ Acts as Stack + Queue Can be used as: Stack (LIFO) Queue (FIFO) Deque (both ends) 🔹 Key Operations ✔ addFirst() / addLast() ✔ removeFirst() / removeLast() ✔ peekFirst() / peekLast() 🔹 When should we use ArrayDeque? 👉 Use ArrayDeque when: ✔ You need fast insertions/deletions at both ends ✔ You want a better alternative to Stack or LinkedList ✔ Performance matters (less overhead) 🔹 When NOT to use? ❌ When you need random access (indexing) ❌ When frequent middle operations are required 🔹 Key Insight 💡 Not all Queues are equal — 👉 Choosing the right implementation (LinkedList vs ArrayDeque) can significantly impact performance. 🔹 Day 53 Realization 🎯 Efficiency isn’t just about solving problems — 👉 It’s about solving them smartly with the right tools. #Java #ArrayDeque #DataStructures #CollectionsFramework #Programming #DeveloperJourney #100DaysOfCode #Day53 Grateful for guidance from, Sharath R TAP Academy
To view or add a comment, sign in
-
-
Day 10/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Polymorphism Polymorphism means “many forms” — the same method behaves differently depending on the object. 💻 Practice Code: 🔸 Example Program class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // Upcasting a.sound(); // Runtime polymorphism } } 📌 Key Learnings: ✔️ Same method → different behavior ✔️ Achieved using method overriding ✔️ Based on object type (runtime) 🎯 Focus: Understanding dynamic behavior using inheritance and method overriding 🔥 Interview Insight: Polymorphism is a core OOP concept and widely used in real-world applications. #Java #100DaysOfCode #Polymorphism #OOP #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 3 of My Coding Challenge Improving my problem-solving skills step by step! Today I solved a number-based problem on reversing an integer. 🔹 Platforms: LeetCode & GeeksforGeeks 🔹 Problem: LeetCode #7 – Reverse Integer 🔹 Problem Statement: Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows, return 0. 🔹 Approach: 1️⃣ Extract last digit using modulo (%) 2️⃣ Build reversed number step by step 3️⃣ Check for overflow before updating result 🔹 Example: Input: 123 → Output: 321 Input: -123 → Output: -321 Input: 120 → Output: 21 🔹 What I learned: ✔ Handling integer overflow conditions ✔ Working with digits using modulo & division ✔ Writing safe and optimized code 💻 Code: import java.util.*; public class ReverseIntegerLeetCode7 { ``` public static int reverse(int x) { int rev = 0; while (x != 0) { int rem = x % 10; x = x / 10; // Check overflow if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && rem > 7)) { return 0; } if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && rem < -8)) { return 0; } rev = (rev * 10) + rem; } return rev; } public static void main(String[] args) { int x = 123; System.out.println(reverse(x)); x = -123; System.out.println(reverse(x)); x = 120; System.out.println(reverse(x)); } ``` } 🔗 GitHub: https://lnkd.in/g-wNSrPq #Java #DSA #LeetCode #CodingChallenge #50DaysChallenge #Consistency #GrowthMindset #LearningJourney
To view or add a comment, sign in
-
Day 62 of Sharing What I’ve Learned🚀 Iterator in Java — Safe and Efficient Traversal After understanding how collections store and organize data, I revisited an important concept — how to safely traverse them using Iterator. 👉 Accessing data is easy… but doing it correctly and safely matters more. 🔹 What is an Iterator? Iterator is an interface in Java used to traverse elements of a collection one by one. 👉 It provides a standard way to loop through: ArrayList HashSet LinkedList And more… 🔹 Why not just use a for loop? Using a normal loop works… but it has limitations: ❌ Not safe when modifying collection ❌ Can lead to ConcurrentModificationException ❌ Not universal for all collection types 👉 That’s where Iterator comes in ✔ 🔹 Key Methods of Iterator hasNext() → checks if next element exists next() → returns the next element remove() → removes the current element safely 🔹 Example import java.util.*; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); Iterator<String> it = list.iterator(); while(it.hasNext()) { String lang = it.next(); System.out.println(lang); } } } 🔹 Real Advantage 💡 👉 Removing elements while iterating: Iterator<String> it = list.iterator(); while(it.hasNext()) { if(it.next().equals("Python")) { it.remove(); // Safe removal } } ✔ No errors ✔ Clean logic ✔ Interview-friendly concept 🔹 Day 62 Realization Traversing data is not just about loops — it’s about doing it safely and efficiently. 👉 Iterator provides better control and prevents runtime issues 👉 Essential when working with dynamic collections #Java #Collections #DataStructures #CollectionsFramework #Iterator #Programming #DeveloperJourney #100DaysOfCode #Day61 Grateful for guidance from, TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
-
Coding agents are innovating fast, but they're also getting bloated. To actually understand what they’re doing, you have to go back to the basics. A good way to learn is to get into it. Adding LSP support to the 260 line nanocode agent in #Java https://lnkd.in/ec5j8QpJ
To view or add a comment, sign in
-
🚀 Day 56: Final & Static — Establishing Rules in Java 🏗️ After exploring the flexibility of Polymorphism yesterday, today was about the "Constants" of Java. I dived into the Final and Static keywords—two tools that help us manage memory and protect our code’s logic. 🔒 1. The Final Keyword: "No Changes Allowed" The final keyword is all about restriction. I learned it can be applied in three ways: ▫️ Final Variables: Creates a constant. Once assigned, the value cannot be changed (e.g., final double PI = 3.14). ▫️ Final Methods: Prevents Method Overriding. If you don't want a subclass to change your logic, you make it final. ▫️ Final Classes: Prevents Inheritance. A final class cannot be extended (like the String class in Java!). 💾 2. The Static Keyword: "Shared by All" The static keyword shifts the focus from "Objects" to the "Class" itself. ▫️ Static Variables: These belong to the class, not the individual objects. Every object of that class shares the exact same variable, which is great for memory efficiency. ▫️ Static Methods: These can be called without creating an object of the class (like Math.sqrt()). ▫️ Static Blocks: Used for initializing static variables when the class is first loaded. Question for the Devs: Do you use final for all your local variables that don't change, or do you find that it makes the code too "noisy"? I'm curious to hear your take on Clean Code vs. Explicit Logic! 👇 #Java #CoreJava #StaticKeyword #FinalKeyword #100DaysOfCode #BackendDevelopment #CleanCode #SoftwareEngineering #LearningInPublic 10000 Coders Meghana M
To view or add a comment, sign in
-
Again, a good article from Sergiy Yevtushenko. Every developer should read this - it's Java, but the lessons are useful in many modern languages. Practical, applied programming tips like many devs appreciate them. These are not just "FP style examples in Java". They are also applied ways of properly decoupling concepts and mechanisms that should remain decoupled, but which traditional OOP languages tend to force us to couple. For example: handling errors with try-catch VS handling errors with Result<>, flatMap() etc. And don't forget to follow Sergiy Yevtushenko, his programming advice is always best of class. #Java #FunctionalProgramming #Programming #Architecture
To view or add a comment, sign in
Explore related topics
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