Day16:- Arrays A Journey with Frontlines EduTech (FLM) and Fayaz S ✒️An array in Java is a data structure used to store multiple values of the same data type in a single variable. ✒️Instead of creating many variables, we store them in one array. Without array:- int a = 10; int b = 20; int c = 30; With array:- int [] numbers = {10,20,30}; Syntax:- dataType[] = new new dataType [size]; Array Initialization and access:- ✒️Arrays can also be initialized with values directly. int[] num = {1,2,3,4,5}; ✒️You can access elements using their index (string Index 0) Looping through arrays:- ✒️You can use loops to traverse arrays. ✒️ Commonly using for or enhanced for loops. ex:- int [] arr = {10,20,30,}; for(int i = 0; i<arr.lenght; i++) { System.out.println(arr[i]); } Advantages of Arrays:- ✒️Arrays allow random access of elements using index. ✒️Arrays are easy to traverse and manipulate using loops. ✒️Arrays help in efficient memory allocation when the size is known. ✒️They store multiple values in a single variable, reducing code complexity. ✒️Arrays are faster in accessing and modifying data compared to some data structures. Two-Dimensional Arrays :- ✒️2D arrays are arrays of arrays. They are useful for matrix-like data representation. Syntax:- dataType[][] arrayName = new dataType[rows][columns]; #arrays #corejava #java #2darrays
Arrays in Java: Data Structure and Syntax
More Relevant Posts
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
Day 14:- Strings A Journey with Frontlines EduTech (FLM) and Fayaz S ✒️ All String objects are store in Heap Area. Strings are write in two ways:- 1. Literals String s = "Tharun"; 2. Object:- ClassName objectName = new ClassName(); String s = new String("Tharun"); ✒️The literals are stored in String constant pool. ✒️The object is store in Head area. ✒️The string constant pool is a special memory area inside the heap where Java stores string literals to save memory and improves performance. ✒️When multiple Strings have the same value, Java stores only one copy in the pool. ✒️The string constant pool saves memory, increases performance and avoids duplicate string object. Day 15:- Type Casting :- ✒️The Type Casting in java means converting one data type into another data type. There are two types:- 1. Implicit type casting 2. Explicit type casting 1. Implicit type casting:- ✒️Converting a smaller data type into a larger data type automatically by java Ex:- byte->short->int->long->float->double 2. Explicit type casting:- ✒️converting a larger data types in to a smaller data type manually using casting. #Strings #java #corejava
To view or add a comment, sign in
-
-
🚀 Day 22/100 – DSA Challenge Today’s problem: Climbing Stairs (LeetCode | Easy | DP) The problem is simple: You can climb either 1 or 2 steps at a time. How many distinct ways are there to reach the top? 🔴 Approach 1: Recursion (Brute Force) 👉 At each step, you have 2 choices: Take 1 step Take 2 steps 📌 Java Code: class Solution { public int climbStairs(int n) { if (n <= 2) return n; return climbStairs(n - 1) + climbStairs(n - 2); } } ⚡ Complexity: Time: O(2ⁿ) ❌ (recomputes subproblems) Space: O(n) (recursion stack) 🟡 Approach 2: Memoization (Top-Down DP) 👉 Store results of subproblems to avoid recomputation 📌 Java Code: class Solution { public int climbStairs(int n) { int[] dp = new int[n + 1]; return helper(n, dp); } private int helper(int n, int[] dp) { if (n <= 2) return n; if (dp[n] != 0) return dp[n]; dp[n] = helper(n - 1, dp) + helper(n - 2, dp); return dp[n]; } } ⚡ Complexity: Time: O(n) ✅ Space: O(n) 🟢 Observation: This problem is essentially the Fibonacci sequence: f(n) = f(n-1) + f(n-2) 🎯 Key Learning: Start with recursion to understand the problem, then optimize using DP to eliminate overlapping subproblems. 📈 Day 22 done—getting better at recognizing DP patterns! #100DaysOfCode #DSA #DynamicProgramming #Java #CodingJourney
To view or add a comment, sign in
-
🚀 Day 23/40 – DSA Challenge 📌 LeetCode Problem – Remove Duplicates from Sorted List 📝 Problem Statement Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the modified linked list. 📌 Example Input: 1 → 1 → 2 → 3 → 3 Output: 1 → 2 → 3 💡 Key Insight Since the list is sorted, 👉 duplicates will always be adjacent. So we don’t need extra space or hashing. 🔥 Optimal Approach – Single Traversal 🧠 Idea Traverse the list and compare: Current node Next node If they are equal → skip the next node Else → move forward 🚀 Algorithm 1️⃣ Start from head 2️⃣ While current != null && current.next != null 3️⃣ If: current.val == current.next.val 👉 Skip duplicate: current.next = current.next.next 4️⃣ Else: Move to next node ✅ Java Code (Optimal O(n)) class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learnings – Day 23 ✔ Sorted data simplifies problems ✔ Linked list manipulation requires careful pointer handling ✔ No extra space needed when duplicates are adjacent ✔ Always check current.next != null to avoid errors Simple structure. Clean pointer logic. Efficient solution. Day 23 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 21/40 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗝𝗮𝘃𝗮 𝘀𝘄𝗶𝘁𝗰𝗵 𝘀𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 𝘁𝘂𝗿𝗻𝗲𝗱 𝟯𝟬 𝘁𝗵𝗶𝘀 𝘆𝗲𝗮𝗿 Here's the short version: What started as a C-style branching construct is now a declarative data-matching engine — and the JVM internals behind it are genuinely fascinating. What I learned going deep on this: → Early switch relied on jump tables — fast, but fall-through bugs were silent and destructive → Java added definite assignment rules, preventing uninitialized variables from slipping through → The JVM picks between tableswitch (O(1)) and lookupswitch (O(log n)) based on how dense your cases are → String switching since Java 7 uses hashCode + equals internally — it's not magic, it's two passes → Java 14 made switch an expression, which killed fall-through at the language level → Modern Java (21+) adds pattern matching with type binding and null handling — code reads like a description of data → invokedynamic enables runtime linking, replacing rigid compile-time dispatch tables → Java 25 enforces unconditional exactness in type matching — no more silent data loss • The real shift isn't syntax. It's the question switch answers. Old: "Where should execution go?" New: "What is the shape of this data?" That's not just a feature upgrade. That's a change in how you think about branching. Which of these surprised you most? Drop it in the comments. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareEngineering #JVM #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
Day 22/100 — Lambda Expressions ⚡ From 5 lines of anonymous class → to just 1 clean line using lambdas. Before: new Runnable() { public void run() { println("Hi"); } }; After: () -> println("Hi"); Same output. ~80% less code, more readability. 💡 Why it matters: Lambdas make your code concise, functional, and easier to maintain—especially when working with collections. 🔹 Common Forms: → No params: () -> code → One param: x -> code → Two params: (x, y) -> code 🔹 Examples: names.sort((a, b) -> a.length() - b.length()); names.forEach(n -> println(n)); names.removeIf(n -> n.length() < 4); 🎯 Challenge: Sort a list by length first, then alphabetically when lengths are equal 👇 names.sort((a, b) -> { if (a.length() == b.length()) { return a.compareTo(b); } return a.length() - b.length(); }); Clean. Powerful. Interview-ready. 🚀 #Java #Lambda #Java8 #CoreJava #100DaysOfCode #100DaysOfJava #Programming #Developers
To view or add a comment, sign in
-
-
Solved: Remove Duplicates from Sorted Array 🔍 Problem Summary: Given a sorted array, remove duplicates in-place such that each unique element appears only once and return the new length. 💡 Approach: ✔️ Used the Two Pointer technique ✔️ One pointer (index) tracks unique elements ✔️ Another pointer (j) scans the array ✔️ When a new element is found, move it forward 👨💻 Code (Java): public int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int index = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[index]) { index++; nums[index] = nums[j]; } } return index + 1; } ⚡ Key Learning: Understanding patterns is more important than memorizing solutions. Sorted array + duplicates → Two Pointer approach works efficiently. 📊 Complexity: ⏱ Time: O(n) 💾 Space: O(1) 📌 Improving step by step—consistency is the goal! #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Learning
To view or add a comment, sign in
-
-
🚀 Day 5/30 — LeetCode Challenge Solved Merge Two Sorted Lists on using Java. This problem focuses on pointer manipulation in linked lists — merging two sorted lists efficiently without creating extra space. ✅ Key takeaway: Understanding how to move and manage pointers is crucial when working with linked data structures. Time Complexity: O(n + m) Space Complexity: O(1) (in-place merge) Building consistency while strengthening fundamentals in data structures. #LeetCode #Java #LinkedList #DataStructures #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
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