#Design a basic URL Shortener service in Java Try Self than check #Solution 1. Functional Requirements: 2. Convert a long URL → short URL 3. Convert a short URL → original long URL 4. Same long URL should always return the same short URL 5. Short URL should be unique and collision-free 6. Handle up to 1 million URLs efficiently Input: encode("https://lnkd.in/geHb6Qua") Output: "http://mahfooz.com/abc123" decode("http://mahfooz.com/abc123") Output: "https://lnkd.in/geHb6Qua" # Constraints 1. Time Complexity: O(1) for encode & decode 2. Space Complexity: Optimize for large data 3. Avoid collisions 4. No external DB (in-memory only) Theory Questions (Must Answer) 1. Why did you choose HashMap? Explain internal working of HashMap What is average & worst-case complexity? 2. How will you avoid collisions? What if two URLs generate same short code? 3. How will you scale this system? If millions of users hit your backend How to move from in-memory → distributed system? 4. Thread Safety Is your solution thread-safe? If not, how will you fix it? 5. Backend Concept If implemented in Spring Boot, how will APIs look? https://lnkd.in/grX_mVes #Java #JavaDeveloper #BackendDeveloper #SoftwareEngineer #CodingInterview #DSA #Programming #Tech #Developers #InterviewPreparation #JavaBackend
Designing a Basic URL Shortener in Java with HashMap
More Relevant Posts
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Streams #Backend #CodingInterview #SpringBoot #Developers #InterviewPrep #CleanCode
To view or add a comment, sign in
-
-
🚀 Java Deep dive : Why does Java have both "int" and "Integer"? At first glance, both store numbers. But in reality — they solve completely different problems. ------ ⚡ "int" → Speed - Primitive type - Stores raw value - Fast & memory efficient - ❌ No null - ❌ No methods 👉 Best for: loops, calculations, performance-critical code --- 🧠 "Integer" → Flexibility - Wrapper class (object) - Can store "null" - Supports utility methods - Works with Collections 👉 Best for: APIs, DB, frameworks, real-world applications --- 🔥 Why Java needed "Integer" Because primitives alone weren’t enough: ✔ Collections require objects ✔ Null handling is essential (DB/API cases) ✔ Utility methods simplify operations ✔ Autoboxing bridges "int" ↔ "Integer" seamlessly --- ⚠️ Interview Trap (Must Know) "Integer" comparison using "==" can break your logic: - Works for -128 to 127 (cached) - Fails outside that range 👉 Always use ".equals()" for comparison --- 🧠 When to use what? ✔ Use "int" → when performance matters ✔ Use "Integer" → when flexibility is needed --- 💬 Comment “JAVA” if you want more such interview-ready concepts 🔗 Open to connect with Backend / Java / Data folks Follow Surya Mahesh Kolisetty for more such backend deep dives. #Java #SystemDesign #InterviewPrep #BackendDeepDive #Cfbr #Connections #SpringBoot #Backend #InterviewPrep #Programming
To view or add a comment, sign in
-
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream #Java #Streams #Backend #SpringBoot #Developers #CleanCode
To view or add a comment, sign in
-
-
🧠 Every time you run Java, a complex system decides your app’s fate. Do you understand it? You write ".java" → compile → run… and boom, output appears. But under the hood? An entire powerful ecosystem is working silently to make your code fast, efficient, and scalable. Here’s what actually happens inside the JVM 👇 ⚙️ 1. Class Loader Subsystem Your code isn’t just “run” it’s carefully loaded, verified, and managed. And yes, it follows a strict delegation model (Bootstrap → Extension → Application). 🧠 2. Runtime Data Areas (Memory Magic) This is where the real game begins: - Heap → Objects live here 🏠 - Stack → Method calls & local variables 📦 - Metaspace → Class metadata 🧾 - PC Register → Tracks execution 🔍 🔥 3. Execution Engine Two heroes here: - Interpreter → Executes line by line - JIT Compiler → Turns hot code into blazing-fast native machine code ⚡ 💡 That’s why Java gets faster over time! ♻️ 4. Garbage Collector (GC) No manual memory management needed. JVM automatically: - Cleans unused objects - Prevents memory leaks - Optimizes performance 📊 Real Talk (Production Insight): Most issues are NOT business logic bugs. They’re caused by: ❌ Memory leaks ❌ GC pauses ❌ Poor heap sizing 🎯 Expert Tip: If you truly understand JVM internals, you’ll debug faster than 90% of developers. 👉 Next time your app slows down, don’t just blame the code… Look inside the JVM. That’s where the truth is. 💬 Curious — how deep is your JVM knowledge on a scale of 1–10? #Java #JVM #JavaJobs #Java26 #CodingInterview #JavaCareers #JavaProgramming #EarlyJoiner #JVMInternals #InterviewPreparation #JobSearch #Coding #JavaDevelopers #LearnWithGaneshBankar
To view or add a comment, sign in
-
-
Iterating a String wrong costs O(n²) — here's the fix. Most Java devs write this without thinking twice: String s = "transaction_id_9823"; for (int i = 0; i < s.length(); i++) { process(s.charAt(i)); } It looks fine. But here's what's actually happening under the hood. ──────────────────────── charAt(i) — Index into the string directly ✅ O(1) per access — no allocation ✅ Zero memory overhead ✅ Lazy — only touches chars you actually use ⚠️ Can get painful if length() is re-evaluated inside old loops toCharArray() — Converts the whole string into a char[] ✅ Clean syntax for enhanced for-loops ✅ Safe for mutation (great for parsing logic) ⚠️ Allocates a full char[] copy — O(n) memory upfront ⚠️ Wasteful if you exit early (e.g. validation short-circuits) ──────────────────────── In our Kafka message validation pipeline, incoming payment strings can be 500+ chars. Switching bulk validators from toCharArray() to charAt() cut heap allocations by ~40% in high-throughput bursts. Rule of thumb: → Read-only iteration? Use charAt() → Need to mutate or pass char[]? Use toCharArray() → Modern Java (11+)? Consider chars() stream for functional style ──────────────────────── What's your default when you iterate a String? Drop it in the comments — curious where the team lands. #Java #CoreJava #StringHandling #FinTech #BackendEngineering
To view or add a comment, sign in
-
-
💡 Java Collections (Revision)— What to Use, When, and What's Happening Internally Most developers use collections daily. Very few understand what's happening under the hood. Here's a clean breakdown 👇 🔹 LIST — Ordered, Allows Duplicates ArrayList ✔ Backed by dynamic array ✔ Fast random access O(1) ✔ Use when: frequent reads, less modification LinkedList ✔ Doubly linked list ✔ Fast insert/delete O(1) ✔ Use when: frequent insertions/deletions 🔹 SET — Unique Elements HashSet ✔ Uses HashMap internally ✔ No order, O(1) operations ✔ Use when: fast lookup, uniqueness LinkedHashSet ✔ HashSet + insertion order ✔ Uses LinkedHashMap internally ✔ Use when: need order + uniqueness TreeSet ✔ Red-Black Tree, sorted order, O(log n) ✔ Use when: sorted data required 🔹 MAP — Key-Value Pairs HashMap ✔ Bucket array + hashing ✔ Linked list → Tree (Java 8+), O(1) avg ✔ Use when: fast key-value access LinkedHashMap ✔ HashMap + doubly linked list ✔ Maintains insertion order ✔ Use when: LRU cache / predictable iteration TreeMap ✔ Red-Black Tree, sorted keys ✔ Use when: sorted map needed ConcurrentHashMap ✔ Thread-safe, CAS + bucket-level locking ✔ Lock-free reads ✔ Use when: multi-threaded systems 🔥 Internal Patterns You Should Know ✔ Hashing converts key to bucket index ✔ Collisions resolved via Linked List then Tree ✔ CAS enables lock-free updates in ConcurrentHashMap ✔ Red-Black Tree keeps operations at O(log n) ✔ Doubly Linked List maintains insertion order ⚠️ Common Mistakes ✔ Using LinkedList for random access ✔ Bad hashCode() causing performance issues ✔ Using HashMap in multithreaded code ✔ Ignoring ordering requirements 🧠 One Line Memory Trick l List → Order + Duplicates Set → No duplicates Map → Key → Value Mastering collections = mastering backend performance. #Java #Collections #DataStructures #SoftwareEngineering #BackendDevelopment #SystemDesign
To view or add a comment, sign in
-
-
🚀 Day 25 – Collections Tuning: Writing High-Performance Java Code Java Collections are powerful — but default usage ≠ optimal performance. As an architect, understanding how to tune collections can significantly impact latency, memory, and scalability. Here’s how to use Collections the right way: 🔹 1. Choose the Right Collection Type ArrayList → Fast reads, slower inserts in middle LinkedList → Rarely useful (avoid in most cases) HashMap → Fast key-based access (O(1)) TreeMap → Sorted data (O(log n)) ➡ Wrong choice = performance bottleneck. 🔹 2. Set Initial Capacity Smartly Avoid repeated resizing: new ArrayList<>(1000); new HashMap<>(1024); ➡ Reduces rehashing & memory reallocations. 🔹 3. Understand Load Factor (HashMap) Default = 0.75 Higher → less memory, more collisions Lower → more memory, better performance ➡ Tune based on use case. 🔹 4. Prefer ArrayList Over LinkedList Better cache locality Faster iteration Lower memory overhead ➡ LinkedList is rarely the right choice in real systems. 🔹 5. Use Concurrent Collections When Needed ConcurrentHashMap → thread-safe without full locking CopyOnWriteArrayList → read-heavy scenarios ➡ Avoid Collections.synchronized* unless necessary. 🔹 6. Avoid Unnecessary Boxing/Unboxing List<Integer> vs int[] ➡ Boxing adds memory + CPU overhead ➡ Use primitive arrays where performance is critical. 🔹 7. Use Streams Carefully Great for readability But avoid in tight loops / high-frequency paths ➡ Sometimes traditional loops are faster. 🔹 8. Optimize Iteration Patterns Prefer for-each over index loops Avoid nested loops on large datasets ➡ Think in terms of algorithmic complexity. 🔹 9. Remove Duplicates Efficiently Set<T> unique = new HashSet<>(list); ➡ O(n) vs O(n²) approaches. 🔥 Architect’s Takeaway Collections tuning is about small optimizations at scale. Done right, it leads to: ✔ Lower latency ✔ Better memory usage ✔ Higher throughput ✔ Scalable systems 💬 How are you tuning Java Collections in your high-performance applications? #100DaysOfJavaArchitecture #Java #Collections #PerformanceTuning #SystemDesign #JavaPerformance #TechLeadership
To view or add a comment, sign in
-
-
equals() vs == Most Java developers learn this lesson the hard way at some point: At first glance, they look similar. But they solve completely different problems. Here is the difference that can save you from bugs: - == compares references (memory address) - equals() compares values (logical equality) Lets make it real: String a = new String("java"); String b = new String("java"); System.out.println(a == b); // false System.out.println(a.equals(b)); // true Why? - a == b checks if both variables point to the SAME object in memory - a.equals(b) checks if both objects have the SAME content Now here is where things get tricky (and dangerous): String x = "java"; String y = "java"; System.out.println(x == y); // true This works because of the String Pool. But relying on this behavior is a mistake. Why this matters in real projects: - Comparing DTOs incorrectly can break business logic - Using == in collections can cause silent failures - Bugs become inconsistent and hard to reproduce Golden rule: - Use == for primitives (int, boolean, etc.) - Use equals() for objects Pro tip: Always override equals() and hashCode() together when creating domain objects. Especially if you use them in collections like HashMap or HashSet. In backend systems, small misunderstandings like this can lead to big production issues. Mastering fundamentals is what separates a developer who writes code... from one who builds reliable systems. #Java #BackendDevelopment #Programming #SoftwareEngineering #CleanCode #JavaTips #CodingBestPractices #Developers #Tech #JavaDeveloper #SystemDesign #CodingLife #LearnToCode
To view or add a comment, sign in
-
-
🚀 𝐖𝐡𝐲 𝐀𝐫𝐞 𝐒𝐭𝐫𝐢𝐧𝐠𝐬 𝐈𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞 𝐢𝐧 𝐉𝐚𝐯𝐚? If you’ve worked with Java, you’ve probably heard this often: 👉 “Strings are immutable.” But have you ever wondered why? Let’s break it down 👇 🔹 1. 𝐒𝐞𝐜𝐮𝐫𝐢𝐭𝐲 🔐 * Strings are heavily used in sensitive areas like file paths, URLs, database connections, and authentication. * Immutability ensures these values can’t be altered once created, preventing unexpected vulnerabilities. 🔹 2. 𝐒𝐭𝐫𝐢𝐧𝐠 𝐏𝐨𝐨𝐥 𝐎𝐩𝐭𝐢𝐦𝐢𝐳𝐚𝐭𝐢𝐨𝐧 💡 * Java uses a String Constant Pool to reuse memory. Example: String a = "hello"; String b = "hello"; Both a and b point to the same object — saving memory efficiently. 🔹 3. 𝐓𝐡𝐫𝐞𝐚𝐝 𝐒𝐚𝐟𝐞𝐭𝐲 🧵 * Since Strings can’t change, they are inherently thread-safe. * No need to worry about synchronization when sharing across threads. 🔹 4. 𝐂𝐚𝐜𝐡𝐢𝐧𝐠 𝐇𝐚𝐬𝐡𝐂𝐨𝐝𝐞 ⚡ * Strings are widely used as keys in HashMaps. * Immutability allows caching of hashcode, making lookups faster. 🔹 5. 𝐏𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝐓𝐫𝐚𝐝𝐞-𝐨𝐟𝐟 ⚖️ * While immutability may create more objects, it avoids side effects and leads to cleaner, predictable code. 💬 𝑷𝒓𝒐 𝑻𝒊𝒑: If you need mutable strings, use: ** StringBuilder (single-threaded) ** StringBuffer (multi-threaded) ✨ 𝐅𝐢𝐧𝐚𝐥 𝐓𝐡𝐨𝐮𝐠𝐡𝐭: 𝘐𝘮𝘮𝘶𝘵𝘢𝘣𝘪𝘭𝘪𝘵𝘺 𝘪𝘴𝘯’𝘵 𝘫𝘶𝘴𝘵 𝘢 𝘥𝘦𝘴𝘪𝘨𝘯 𝘤𝘩𝘰𝘪𝘤𝘦 — 𝘪𝘵’𝘴 𝘢 𝘱𝘰𝘸𝘦𝘳𝘧𝘶𝘭 𝘤𝘰𝘯𝘤𝘦𝘱𝘵 𝘵𝘩𝘢𝘵 𝘮𝘢𝘬𝘦𝘴 𝘑𝘢𝘷𝘢 𝘢𝘱𝘱𝘭𝘪𝘤𝘢𝘵𝘪𝘰𝘯𝘴 𝘮𝘰𝘳𝘦 𝘴𝘦𝘤𝘶𝘳𝘦, 𝘦𝘧𝘧𝘪𝘤𝘪𝘦𝘯𝘵, 𝘢𝘯𝘥 𝘳𝘦𝘭𝘪𝘢𝘣𝘭𝘦. #Java #BackendDevelopment #Programming #SoftwareEngineering #TechConcepts #JavaDeveloper
To view or add a comment, sign in
-
-
𝗝𝗗𝗞 𝘃𝘀 𝗝𝗥𝗘 𝘃𝘀 𝗝𝗩𝗠 Here's what actually happens when you run a Java program — and the parts most engineers never learn: JDK → JRE → JVM → JIT 𝗝𝗗𝗞 (Java Development Kit) Your complete toolbox. Compiler (javac), debugger, profiler, keytool, jshell — and a bundled JRE. Without it, you can't write or compile Java. Just run it. 𝗝𝗥𝗘 (Java Runtime Environment) JVM + standard class libraries. Ships to end users. No compiler. No dev tools. Just enough to run a .jar. 𝗝𝗩𝗠 (Java Virtual Machine) This is where it gets interesting. 𝗧𝗵𝗿𝗲𝗲 𝗹𝗮𝘆𝗲𝗿𝘀 𝗶𝗻𝘀𝗶𝗱𝗲: • Class Loader — loads, links, and initializes .class files at runtime (not all at startup) • Runtime Data Areas — Heap, Stack, Method Area, PC Register, Native Method Stack • Execution Engine — interprets + compiles bytecode 𝗝𝗜𝗧 (Just-In-Time Compiler) Watches your code at runtime. Identifies "hot" methods — those called frequently. Compiles them natively. Skips the interpreter next time. That's how Java catches up to C++ performance on long-running workloads. 𝗪𝗵𝗮𝘁 𝗺𝗼𝘀𝘁 𝗱𝗲𝘃𝘀 𝗺𝗶𝘀𝘀 • 𝗖𝗹𝗮𝘀𝘀 𝗟𝗼𝗮𝗱𝗶𝗻𝗴 𝗶𝘀 𝗹𝗮𝘇𝘆 The JVM doesn't load all classes upfront. It loads them on first use — which is why cold start time differs from steady-state throughput. • 𝗝𝗜𝗧 𝗵𝗮𝘀 𝘁𝗶𝗲𝗿𝘀 HotSpot JVM uses tiered compilation: C1 (fast, light optimization) kicks in first, then C2 (aggressive optimization) takes over for truly hot code. GraalVM replaces C2 entirely with a more powerful compiler. • 𝗧𝗵𝗲 𝗛𝗲𝗮𝗽 𝗶𝘀 𝗻𝗼𝘁 𝗼𝗻𝗲 𝘁𝗵𝗶𝗻𝗴 It's split: Eden → Survivor Spaces → Old Gen → Metaspace (post Java 8). Understanding this is prerequisite to tuning GC and fixing OOM errors. • 𝗦𝘁𝗮𝗰𝗸 𝘃𝘀 𝗛𝗲𝗮𝗽 — 𝗿𝘂𝗻𝘁𝗶𝗺𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 Every thread gets its own stack. Local primitives live there. Objects always go to the heap. References live on the stack. This is why stack overflows (deep recursion) and heap OOMs are completely different problems. • 𝗝𝗩𝗠 𝗶𝘀 𝗻𝗼𝘁 𝗮𝗹𝘄𝗮𝘆𝘀 𝗶𝗻𝘁𝗲𝗿𝗽𝗿𝗲𝘁𝗲𝗱 When GraalVM's native-image compiles your app ahead-of-time (AOT), there's no JVM at runtime at all. Instant startup. Fixed memory footprint. Different trade-offs. • 𝗕𝘆𝘁𝗲𝗰𝗼𝗱𝗲 𝗶𝘀 𝗻𝗼𝘁 𝗯𝗶𝗻𝗮𝗿𝘆 It's an intermediate representation — platform-agnostic instructions the JVM can run on any OS. This is Java's "write once, run anywhere" in practice, not just in theory. 𝗧𝗵𝗲 𝗺𝗲𝗻𝘁𝗮𝗹 𝗺𝗼𝗱𝗲𝗹 𝘁𝗵𝗮𝘁 𝗰𝗹𝗶𝗰𝗸𝘀: • JDK = write + compile + run • JRE = run only • JVM = execution environment • JIT = runtime optimizer What's the JVM internals detail that surprised you most when you first learned it? A special thanks to my faculty Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #JVM #SoftwareEngineering #BackendDevelopment #ProgrammingFundamentals
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