Here’s🚀 Coding Interview Questions + Answers (Part 2) (Java 🧑💻 Python | Medium Level) If you can solve these, you're already ahead of 70% candidates 👇 --- 🔹 11. Second Largest Element Java: int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for(int n : arr){ if(n > first){ second = first; first = n; } else if(n > second && n != first){ second = n; } } Python: arr = [1,5,3,9,7] print(sorted(set(arr))[-2]) --- 🔹 12. Remove Duplicates Java: Set<Integer> set = new LinkedHashSet<>(list); Python: list(set(arr)) --- 🔹 13. Missing Number (1–n) Java: int sum = n*(n+1)/2; int actual = Arrays.stream(arr).sum(); System.out.println(sum - actual); Python: n = 5 arr = [1,2,3,5] print(n*(n+1)//2 - sum(arr)) --- 🔹 14. Merge Sorted Arrays Java: int i=0,j=0; while(i<a.length && j<b.length){ if(a[i]<b[j]) System.out.print(a[i++]); else System.out.print(b[j++]); } Python: a=[1,3,5]; b=[2,4,6] print(sorted(a+b)) --- 🔹 15. Character Frequency Java: Map<Character,Integer> map = new HashMap<>(); for(char c: str.toCharArray()) map.put(c, map.getOrDefault(c,0)+1); Python: from collections import Counter print(Counter("test")) --- 🔹 16. Anagram Check Java: char[] a = s1.toCharArray(); char[] b = s2.toCharArray(); Arrays.sort(a); Arrays.sort(b); System.out.println(Arrays.equals(a,b)); Python: print(sorted(s1)==sorted(s2)) --- 🔹 17. Move Zeros to End Java: int j=0; for(int i=0;i<arr.length;i++) if(arr[i]!=0) arr[j++]=arr[i]; Python: arr = [0,1,0,3] res = [x for x in arr if x!=0] + [0]*arr.count(0) --- 🔹 18. First Non-Repeating Character Java: for(char c: str.toCharArray()) if(str.indexOf(c)==str.lastIndexOf(c)) System.out.println(c); Python: for c in s: if s.count(c)==1: print(c); break --- 🔹 19. Sort Without Inbuilt Java (Bubble Sort): for(int i=0;i<n;i++) for(int j=0;j<n-i-1;j++) if(arr[j]>arr[j+1]){ int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } Python: for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] --- 🔹 20. Common Elements Java: Set<Integer> set = new HashSet<>(); for(int n : arr1) set.add(n); for(int n : arr2) if(set.contains(n)) System.out.println(n); Python: print(set(a) & set(b)) --- 💡 Pro Tip: 👉 These are pattern-based questions 👉 Master them once → reuse in multiple interviews --- 🎯 Next: Part 3 (Advanced 🔥) Comment “PART 3” Follow Sri Harish Chintha for more information Watsup channel… https://lnkd.in/grR24xHU Instagram : https://lnkd.in/gdm-2PuD #Coding #Java #Python #InterviewPrep #Developers #LeetCode #SDE
Coding Interview Questions and Answers in Java and Python
More Relevant Posts
-
🚀 #Coding Interview Questions + FULL CODE (Part 4 🔥) (Java 🧑💻 Python | Real Interview Level) 🔹 28. LRU Cache (Core Idea) 👉 Use HashMap + Doubly Linked List 👉 O(1) get & put (Python shortcut) from collections import OrderedDict --- 🔹 29. Word Count Java: Map<String,Integer> map=new HashMap<>(); for(String w:str.split(" ")) map.put(w,map.getOrDefault(w,0)+1); Python: from collections import Counter print(Counter(s.split())) --- 🔹 30. Kadane’s Algorithm (Max Subarray) Java: int max=arr[0], curr=arr[0]; for(int i=1;i<arr.length;i++){ curr=Math.max(arr[i],curr+arr[i]); max=Math.max(max,curr); } Python: curr=max_sum=nums[0] for n in nums[1:]: curr=max(n,curr+n) max_sum=max(max_sum,curr) --- 🔹 31. Longest Substring (Sliding Window) 👉 Use Set + Two Pointers Java: Set<Character> set = new HashSet<>(); Python: while s[r] in set: remove left --- 🔹 32. Binary Search 👉 O(log n) – MUST know Java: mid = (l+r)/2 Python: mid = (l+r)//2 --- 🔹 33. Two Sum 👉 HashMap = O(n) Java: map.containsKey(target - num) Python: if target-n in dict --- 🔹 34. Valid Parentheses 👉 Stack pattern Java: push → pop → match Python: use dict for pairs --- 🔹 35. Reverse Linked List 👉 Pointer reversal Java/Python: prev → curr → next --- 🔹 36. Detect Loop 👉 Floyd Cycle (fast & slow) --- 🔹 37. Stack Implementation 👉 Array / List --- 🔹 38. LRU Cache 👉 HashMap + Doubly LinkedList 👉 Python: OrderedDict shortcut --- 🔹 39. Word Count 👉 Map / Counter --- 🔹 40. Kadane’s Algorithm 👉 Max Subarray (very important 🔥) Logic: curr = max(num, curr+num) --- 💡 Reality Check: 👉 70% interviews repeat these patterns 👉 If you master this → you're ahead --- 🎯 Done all 4 parts? You’re NOT a beginner anymore 🚀 Comment “PDF” for full notes + code Follow Sri Harish Chintha for more helpful content Watsup channel… https://lnkd.in/grR24xHU Instagram : https://lnkd.in/gdm-2PuD Twitter: https://lnkd.in/g9-KpWcq #Coding #Java #Python #InterviewPrep #FAANG #LeetCode #SDET #Developers #100DaysOfCod
To view or add a comment, sign in
-
🚀 Java for LLM Fine-Tuning & Agents? Yes — It’s Not Just a Python Game. When we talk about Large Language Models (LLMs), one language dominates the conversation: Python. Frameworks like PyTorch, TensorFlow, and Hugging Face Transformers have made it the default choice. But here’s the uncomfortable truth => 👉 Python is not the only serious option anymore. 👉 Java is quietly becoming a strong contender for building and fine-tuning LLM-powered agents. Let’s break it down in a simple, practical way. Why Everyone Defaults to Python ? Massive AI ecosystem Fast prototyping Tons of pretrained models Community support Great for research and experimentation. But production? That’s another story. Where Java Shines (and Why It Matters) 1. Reliability & Stability Java has powered enterprise systems for decades. When you’re deploying fine-tuned models in production, stability matters more than experimentation. Strong typing = fewer runtime surprises Mature memory management Proven scalability Your AI agent doesn’t just work — it keeps working. 2. Performance & Scalability Compared to Python: Better multithreading Lower latency in high-load systems More predictable performance Frameworks like: Deep Java Library (DJL), ONNX Runtime allow you to run and even fine-tune models efficiently in Java environments. 3. Enterprise Integration (This is the BIG one) Most real-world systems already run on: Spring Boot Apache Kafka Hibernate Using Java for LLM agents means: No need for complex Python microservices Easier integration with existing systems Better governance & security 4. Java for LLM Agents (Not Just Models) Agent-based architectures (planning, reasoning, tool usage) are becoming the norm. Java frameworks are catching up fast: LangChain4j Spring AI You can build: Autonomous agents, Tool-integrated workflows, Retrieval-Augmented Generation (RAG) systems 🔧 But What About Fine-Tuning? Let’s be clear: Python still dominates training pipelines BUT Java excels in: Model serving Inference optimization Post-training adaptation (prompt tuning, RAG, adapters) With tools like: ONNX, TensorFlow Java 👉 You can: Export fine-tuned models Run them efficiently in Java Integrate them directly into business workflows The Real Takeaway 💡 It’s not Python vs Java. 💡 It’s Python for experimentation + Java for production AI systems. If your goal is: Reliable AI agents Scalable enterprise deployment Maintainable long-term systems 📚 References & Further Reading DJL Documentation (Deep Java Library) ONNX Runtime Performance Benchmarks LangChain4j & Spring AI GitHub repositories Hugging Face model export & deployment guides #AI #ArtificialIntelligence #MachineLearning #LLM #GenerativeAI #AIAgents #LLMOps #Java #JavaDevelopment #SpringBoot #BackendDevelopment #SoftwareEngineering #LangChain #LangChain4j #SpringAI #ONNX #DeepLearning #MLOps
To view or add a comment, sign in
-
-
Let’s address the elephant in the room: the pitfalls of using asynchronous programming in #Python. It’s often sold as a performance silver bullet, but in reality? It’s an architectural minefield that can turn a simple project into an existential crisis. Spoiler alert: Python’s async environment isn't a "native state"—it’s an add-on. And when you try to mix it with traditional synchronous code, it feels like trying to mix oil, water, and shattered glass. 😅 I recently felt this pain firsthand 🥲 . I was working on a project where some libraries were hard-coded to be async, forcing my routes to be async def. But my database layer? Strictly sync. The result? The sync database completely blocked Python’s event loop. Suddenly, my "blazing fast" API needed a duct-tape architecture of manual threadpools (shoutout to "run_in_threadpool" and "anyio.from_thread.run") just to stay alive. This exposes Python’s biggest concurrency headache: The "Function Color" Problem. In Python, synchronous code and asynchronous code live in two different, incompatible worlds. Because Python's async environment was bolted on later via libraries like asyncio, mixing the two paradigms usually results in fragmented codebases and performance bottlenecks. Compare this to how beautifully other languages handle it: 🟢 Node.js (JavaScript): Built from day one with an always-on, implicit event loop. The entire ecosystem is natively non-blocking. It doesn't force you to manually juggle threadpools for database calls; it just effortlessly directs the traffic. 🔵 Golang: It destroys the "colored function" problem. Go uses lightweight "goroutines" that run in parallel. You don't even have to think about async or await keywords—the Go runtime handles the blocking seamlessly under the hood. So, for the freshers and tech leaders out there, here is your practical gateway on what to choose: Choose Python IF: Your core product revolves around AI, Data Science, or heavy CPU-bound math. (Pro-tip: if your DB and libraries are sync, just stick to plain sync Python! FastAPI's default threadpool handles it perfectly). 🌐 Choose Node.js IF: Your application is I/O heavy (lots of database queries, external API calls, real-time chat). Its async ecosystem is incredibly mature, unified, and painless. 🐹 Choose Golang IF: You need massive, highly-performant backend concurrency and scalability without the cognitive load of managing async/await syntax. Async Python is powerful, but it’s an add-on, not a native state of mind. Choose the ecosystem that fits your architecture, not the other way around. Has anyone else fought the FastAPI + Sync DB battle? Let’s vent in the comments! 👇 #Python #FastAPI #Nodejs #Golang #SoftwareArchitecture #WebDevelopment
To view or add a comment, sign in
-
-
✅ *Top Python Basics Interview Q&A - Part 2* 🚀 *1️⃣ What are functions in Python?* Functions are reusable blocks of code that perform specific tasks. They are defined using the `def` keyword and can take parameters. ``` def greet(name): return f"Hello, {name}!" print(greet("Sahil")) # Output: Hello, Sahil! ``` *2️⃣ What is the difference between lists and tuples?* Lists are mutable (can be changed) and use square brackets `[]`. Tuples are immutable (cannot be changed) and use parentheses `()`. *3️⃣ What are dictionaries in Python?* Dictionaries store data as key-value pairs using curly braces `{}`. Keys must be unique and immutable. ``` person = {"name": "Abhinav", "city": "Pune"} print(person["name"]) # Output: Abhinav ``` *4️⃣ Explain Python strings and common methods.* Strings are immutable sequences of characters enclosed in quotes. Common methods: `.upper()`, `.lower()`, `.split()`, `.replace()`. *5️⃣ What are Python modules?* Modules are Python files with reusable code (`import math`). Packages are directories of modules with `__init__.py`. *6️⃣ How do you handle exceptions in Python?* Use `try-except` blocks to catch and handle errors gracefully. ``` try: num = int(input("Enter number: ")) except ValueError: print("Invalid input!") ``` *7️⃣ What is the difference between `==` and `is`?* `==` compares values; `is` compares object identity (memory location). *8️⃣ What are lambda functions?* Anonymous one-line functions using `lambda` keyword. ``` square = lambda x: x*x print(square(5)) # Output: 25 ``` *9️⃣ Explain range() function.* `range(start, stop, step)` generates sequences of numbers. Commonly used in `for` loops. *🔟 What is PEP 8?* Python's official style guide for readable code (indentation, naming conventions, line length).
To view or add a comment, sign in
-
✅ *Top Coding Interview Questions with Answers: Part-1* 💻🧠 *1️⃣ Reverse a String* *Q:* Write a function to reverse a string. *Python:* ```python def reverse_string(s): return s[::-1] ``` *C++:* ```cpp string reverseString(string s) { reverse(s.begin(), s.end()); return s; } ``` *Java:* ```java String reverseString(String s) { return new StringBuilder(s).reverse().toString(); } ``` *2️⃣ Check for Palindrome* *Q:* Check if a string is a palindrome. *Python:* ```python def is_palindrome(s): s = s.lower().replace(" ", "") return s == s[::-1] ``` *C++:* ```cpp bool isPalindrome(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); s.erase(remove(s.begin(), s.end(), ' '), s.end()); return s == string(s.rbegin(), s.rend()); } ``` *Java:* ```java boolean isPalindrome(String s) { s = s.toLowerCase().replaceAll(" ", ""); return s.equals(new StringBuilder(s).reverse().toString()); } ``` *3️⃣ Count Vowels in a String* *Q:* Count number of vowels in a string. *Python:* ```python def count_vowels(s): return sum(1 for c in s.lower() if c in "aeiou") ``` *C++:* ```cpp int countVowels(string s) { int count = 0; for (char c: s) { c = tolower(c); if (string("aeiou").find(c)!= string::npos) count++; } return count; } ``` *Java:* ```java int countVowels(String s) { int count = 0; s = s.toLowerCase(); for (char c : s.toCharArray()) { if ("aeiou".indexOf(c) != -1) count++; } return count; } ``` *4️⃣ Find Factorial (Recursion)* *Q:* Find factorial using recursion. *Python:* ```python def factorial(n): return 1 if n <= 1 else n * factorial(n - 1) ``` *C++:* ```cpp int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } ``` *Java:* ```java int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } ``` *5️⃣ Find Duplicate Elements in List/Array* *Q:* Print all duplicates from a list. *Python:* ```python from collections import Counter def find_duplicates(lst): return [k for k, v in Counter(lst).items() if v > 1] ``` *C++:* ```cpp vector<int> findDuplicates(vector<int>& nums) { unordered_map<int, int> freq; vector<int> res; for (int n : nums) freq[n]++; for (auto& p : freq) if (p.second > 1) res.push_back(p.first); return res; } ``` *Java:* ```java List<Integer> findDuplicates(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> result = new ArrayList<>(); for (int n : nums) map.put(n, map.getOrDefault(n, 0) + 1); for (Map.Entry<Integer, Integer> entry : map.entrySet()) if (entry.getValue() > 1) result.add(entry.getKey()); return result; } ``` *💻✅💯
To view or add a comment, sign in
-
𝙇𝙖𝙯𝙮 𝘾𝙤𝙢𝙥𝙡𝙚𝙭𝙞𝙩𝙮: Here is a good example for the Python programming language, taken from a comment on a PEP (Python Enhancement Proposal). Someone wrote, about PEP 503: "This PEP is a historical document. The up-to-date, canonical spec, Simple repository API, is maintained on the PyPA specs page." This is NOT true. PEP 503 is completely valid standard used daily by every Python programmer in the whole world. It just explains to everyone, how to access Python packages on the web. And guess what... Do you know how PEP 503 is called? 𝗦𝗶𝗺𝗽𝗹𝗲 𝗥𝗲𝗽𝗼𝘀𝗶𝘁𝗼𝗿𝘆 𝗔𝗣𝗜. That's right: 𝗦𝗶𝗺𝗽𝗹𝗲. PEP 503 is 𝘁𝗿𝘂𝗲, it is 𝘀𝗶𝗺𝗽𝗹𝗲, and it is 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻𝗮𝗹. And more importantly 𝗶𝘁 𝘄𝗮𝘀 𝘁𝗿𝘂𝗲, and it 𝘄𝗶𝗹𝗹 𝗯𝗲 𝘁𝗿𝘂𝗲 in the future. Not like those later "specs" that keep changing overnight. I dare to say, all the cathedral of complexity that was built to handle Python packages, that's 𝙇𝙖𝙯𝙮 𝘾𝙤𝙢𝙥𝙡𝙚𝙭𝙞𝙩𝙮. The result is just too complex for what it's supposed to do. Actually, the cathedral is falling apart: it has become so complex that it's no longer usable. And the reason why that cathedral of workarounds was built around Python packages in the first place, is that no one was willing to face the truth that PEP 503 had been telling them all along: that all Python packages already have clearly identified versions. 𝘐𝘵'𝘴 𝘢 𝘴𝘪𝘮𝘱𝘭𝘦 𝘱𝘳𝘰𝘣𝘭𝘦𝘮 𝘸𝘪𝘵𝘩 𝘢 𝘴𝘪𝘮𝘱𝘭𝘦 𝘴𝘰𝘭𝘶𝘵𝘪𝘰𝘯. It has already been solved dozen of times. The solution is called "caching". Instead, someone preferred to bury PEP 503, possibly the most important PEP on Python packages, under a misleading and degrading comment. Or perhaps, hiding the simplicity of Python packages under a huge mystical temple that no one would be able to grasp, was going to boost someone's ego? Here is the simplicity: there should no need to have "virtual environments" and all that fuss and clutter, when we have PEP 503... on condition that 1. local libraries contain the version number of the package 2. the package name is the package name, and is the import name at the same time. The best thing that Python could do would be to ditch that useless cathedral, without remorse, and keep PEP 503. The only thing that PEP 503 is not not mentioning is the json description file that goes with all Python repositories. But that's easy for everyone to see. The motto is: 𝗥𝗲𝗱𝘂𝗰𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝘁𝗼 𝗮 𝗺𝗶𝗻𝗶𝗺𝘂𝗺. KISS. https://lnkd.in/eEgiXQg7
To view or add a comment, sign in
-
-
"...it may well make sense to experiment in a language like Python. But when it’s time to move from experimentation to production, Java is ready for building AI" by Mary Branscombe #java #ai #softwaredevelopment https://lnkd.in/gU3xb2X4
To view or add a comment, sign in
-
Python Coding in AI projects is similar to how we had Java ~30 years back. Java Servlet - 1997. Very messy, cluttered coding to generate entire HTML ouput ----------------------- out.println("<HTML>"); out.println("<BODY>"); out.println("Hello "+ personResultSet.getName()); out.println("</BODY>"); out.println("</HTML>"); ------------------------ Java Server Pages JSP - Much Cleaner. ------------------------ <HTML> BODY Hello <%= personResultSet.getName()%> </BODY> </HTML> ------------------------ What is your Python coding style in your AI project?
To view or add a comment, sign in
-
🐍 Master Python OOP – Advanced Interview Q&A (Save This!) Preparing for Python interviews? Here are advanced OOP questions & answers + study resources you must know 🚀 🧠 1. What is OOP in Python? ✔ Object-Oriented Programming is a paradigm based on objects, classes, and methods ✔ Helps in writing reusable, scalable, and structured code 🔐 2. What is Encapsulation? ✔ Binding data + methods together ✔ Restrict access using private/protected variables 👉 Example: _protected, __private 🧬 3. What is Inheritance? ✔ One class inherits properties of another ✔ Promotes code reusability Types: ✔ Single ✔ Multiple ✔ Multilevel 🎭 4. What is Polymorphism? ✔ Same function name, different behavior 👉 Example: Method Overriding 🧩 5. What is Abstraction? ✔ Hiding implementation details ✔ Showing only essential features 👉 Achieved using abstract classes (abc module) ⚙️ 6. What are Magic (Dunder) Methods? ✔ __init__, __str__, __len__ ✔ Define object behavior 🔄 7. What is Method Overriding? ✔ Child class modifies parent class method ➕ 8. Method Overloading in Python? ❌ Not directly supported ✔ Use default arguments 🧵 9. What is Multiple Inheritance? ✔ A class inherits from multiple classes 👉 Watch out for MRO 📌 10. What is MRO? ✔ Method Resolution Order defines search path ✔ Use ClassName.mro() 🧠 11. Class vs Instance Variables ✔ Class → Shared ✔ Instance → Unique 🧠 12. Static vs Class Methods ✔ @staticmethod → No class/instance access ✔ @classmethod → Uses cls 🚨 13. Constructor in Python ✔ __init__() initializes objects ⚡ 14. __str__ vs __repr__ ✔ __str__ → User-readable ✔ __repr__ → Debug-focused 🌐 Study Resources • freeCodeCamp https://lnkd.in/gMqHidXr • W3Schools Python OOP https://lnkd.in/gQyfuh7X • GeeksforGeeks OOP in Python https://lnkd.in/gtAfT3ig • Real Python https://realpython.com • Programiz Python OOP https://lnkd.in/gmTJC6n3 • Coursera (Python Courses) https://www.coursera.org 🎯 Pro Tips ✔ Practice real coding examples ✔ Focus on concepts, not memorization ✔ Build mini-projects using OOP ✔ Prepare with mock interviews 🔥 Mastering OOP = Strong coding foundation + Interview success ✍️ About Me Susmitha Chakrala | Professional Resume Writer & LinkedIn Branding Expert Helping students & professionals with: 📄 ATS-Optimized Resumes 🔗 LinkedIn Profile Optimization 💬 Interview Preparation Guidance 📩 DM me for resume & career support #Python #OOP #CodingInterview #Programming #Developers #TechCareers #CareerGrowth 🚀
To view or add a comment, sign in
-
-
Don't choose Python . . . . If you don't know why you are choosing python. Let us tell you why you should choose python ? Just think by yourself na ! Would you carry camera, torch, calculator separately or will carry a smartphone only. Exactly. Python is that one tool that does it all—from automating boring stuff to powering rockets at NASA. Let's go deep - 1. Easy to learn but not easy to outgrow Simplicity does not mean weakness. It lets you focus on solving problems instead of fighting syntax while opening doors to AI, data, and real applications. 2. Works across domains Web development, data science, AI, automation, cloud, testing. One language, multiple use cases. 3. Write once, run anywhere Works across Windows, macOS, and Linux without unnecessary friction. 4. Built for the AI era The most obvious future. AI speaks Python. Tools like TensorFlow, PyTorch, and scikit-learn make it the default choice. 5. Massive ecosystem Thousands of libraries mean you rarely start from scratch. BeautifulSoup for scraping, Flask and FastAPI for APIs, Selenium for automation, Matplotlib for visualization. You build faster and smarter. 6. Flexible and integrative Works with C, Java, and .NET through CPython, Jython, and IronPython. It adapts instead of replacing. Basically, the potato of programming. Mix it with anything, it still delivers. 7. Strong in automation It does not let you get bored. Handles repetitive tasks so you can focus on what actually matters and what creates impact. 8. High career value This is where you get excited. This language will pay your bills and let you chill. One of the most in-demand and highest paying skills in the industry. So basically : -> Java devs write essays -> Python devs write haikus Both get the job done, one's just way less painful So what do you think? Are you choosing the python or not ?
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