Programming Problems and Solutions

Programming problems and solutions for interview practice: arrays, strings, searching, hashing, and classic warm-ups with compiler-style code and outputs.

PragadeeshSeptember 8, 2026
Programming Problems and Solutions
Summarize this article in
Quick Answer
  • 50 solved problems with approach, code, and output - a practice gym, not a theory dump.
  • Start here after you know language syntax. Then add DSA patterns.
  • Every problem is a common OA or round-one warm-up.
  • Copy the compiler block, then retype from memory the next day.
  • Company-wise flavour is on a separate page.

Programming problems and solutions in 2026 cover the theory, patterns, and spoken answers Chennai fresher panels expect before you touch an IDE. This hub at Programming problems and solutions (no number in the URL) gives every answer with a direct first sentence you can say in under a minute.

Last updated: September 9, 2026 - Reviewed by Asmorix mentors in Chennai

Asmorix mentors compiled these from TCS/Infosys services drives, GCC captives on OMR, and product screens across Guindy. Each item below is statement, approach, then runnable code - theory lives on DSA interview questions. Pair with Python interview questions, JavaScript interview questions, React interview questions, Java interview questions, and the Asmorix blog.

How to Use This Problem Set (2026)

  1. Read statement and write approach in 3 bullets before viewing code.
  2. Code without looking, run sample, then compare IDE solution.
  3. State time/space aloud - link to coding interview questions for round habits.
  4. After 50, pick 10 for timed 25-minute reps before company OAs.

Array and String Problems (Q1-Q20)

1. Reverse a string

Statement: Given string s, return reversed s. Approach: Two pointers swap from both ends O(n) time O(n) if new string.

def reverse_str(s):
    arr = list(s)
    lo, hi = 0, len(arr)-1
    while lo < hi:
        arr[lo], arr[hi] = arr[hi], arr[lo]
        lo += 1; hi -= 1
    return ''.join(arr)
print(reverse_str('hello'))
Outputolleh

2. Check palindrome

Statement: Return true if string reads same forward and backward. Approach: Two pointers compare chars at lo/hi moving inward O(n).

def is_pal(s):
    lo, hi = 0, len(s)-1
    while lo < hi:
        if s[lo] != s[hi]:
            return False
        lo += 1; hi -= 1
    return True
print(is_pal('madam'))
OutputTrue

3. Check anagram

Statement: Two strings anagram if same letter counts. Approach: Frequency array size 26 or Counter compare O(n).

from collections import Counter
def is_anagram(a, b):
    return Counter(a) == Counter(b)
print(is_anagram('listen','silent'))
OutputTrue

4. Two sum indices

Statement: Return indices of two numbers adding to target. Approach: Hash map store value to index O(n) time O(n) space.

def two_sum(nums, t):
    seen = {}
    for i, x in enumerate(nums):
        if t-x in seen:
            return seen[t-x], i
        seen[x] = i
    return []
print(two_sum([2,7,11,15], 9))
Output(0, 1)

5. Find duplicate in array

Statement: Array n+1 size values 1..n, one duplicate exists. Approach: Floyd cycle or mark indices negative O(n) O(1).

class Dup {
    static int find(int[] a) {
        int slow = a[0], fast = a[0];
        do { slow = a[slow]; fast = a[a[fast]]; } while (slow != fast);
        slow = a[0];
        while (slow != fast) { slow = a[slow]; fast = a[fast]; }
        return slow;
    }
    public static void main(String[] args) {
        System.out.println(find(new int[]{1,3,4,2,2}));
    }
}
Output2

6. Second largest element

Statement: Find second largest distinct value in unsorted array. Approach: Track first and second max in one pass O(n).

def second_largest(nums):
    first = second = float('-inf')
    for x in nums:
        if x > first:
            second, first = first, x
        elif first > x > second:
            second = x
    return second
print(second_largest([12,35,1,10,34,1]))
Output34

7. Rotate array right by k

Statement: Rotate nums right k steps. Approach: Reverse whole, reverse first k, reverse rest O(n) in-place.

class Rot {
    static void rev(int[] a,int l,int r){while(l<r){int t=a[l];a[l]=a[r];a[r]=t;l++;r--;}}
    static void rotate(int[] a,int k){
        k%=a.length; rev(a,0,a.length-1); rev(a,0,k-1); rev(a,k,a.length-1);
    }
    public static void main(String[] args){
        int[] a={1,2,3,4,5,6,7}; rotate(a,3);
        for(int x:a) System.out.print(x+" ");
    }
}
Output5 6 7 1 2 3 4

8. Maximum subarray sum (Kadane)

Statement: Find max sum contiguous subarray. Approach: Track cur and best ending here O(n) O(1).

def max_sub(nums):
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur+x)
        best = max(best, cur)
    return best
print(max_sub([-2,1,-3,4,-1,2,1,-5,4]))
Output6

9. Missing number 0..n

Statement: Array length n contains n distinct numbers from 0..n, one missing. Approach: Sum formula n*(n+1)/2 minus array sum O(n).

def missing(nums):
    n = len(nums)
    return n*(n+1)//2 - sum(nums)
print(missing([3,0,1]))
Output2

10. Merge overlapping intervals

Statement: Merge all overlapping [start,end] intervals. Approach: Sort by start, merge if overlap O(n log n).

import java.util.*;
class Merge {
    static int[][] merge(int[][] a){
        Arrays.sort(a, Comparator.comparingInt(x->x[0]));
        List<int[]> out=new ArrayList<>();
        for(int[] iv:a){
            if(out.isEmpty()||out.get(out.size()-1)[1]<iv[0]) out.add(iv);
            else out.get(out.size()-1)[1]=Math.max(out.get(out.size()-1)[1],iv[1]);
        }
        return out.toArray(new int[0][]);
    }
    public static void main(String[] args){
        System.out.println(Arrays.deepToString(merge(new int[][]{{1,3},{2,6},{8,10}})));
    }
}
Output[[1, 6], [8, 10]]

11. Valid parentheses

Statement: Return true if brackets balanced. Approach: Stack push open, pop match close O(n).

def valid(s):
    st=[]; m={')':'(',']':'[','}':'{'}
    for c in s:
        if c in m:
            if not st or st.pop()!=m[c]: return False
        else: st.append(c)
    return not st
print(valid('{[]}'))
OutputTrue

12. Implement stack with array

Statement: Support push pop top empty O(1). Approach: Array with top index increment/decrement.

class MyStack {
    int[] a; int t=-1;
    MyStack(int cap){ a=new int[cap]; }
    void push(int x){ a[++t]=x; }
    int pop(){ return a[t--]; }
    int top(){ return a[t]; }
    boolean empty(){ return t<0; }
    public static void main(String[] args){
        MyStack s=new MyStack(10); s.push(5); s.push(9);
        System.out.println(s.pop());
    }
}
Output9

13. Character frequency

Statement: Count frequency of each char in string. Approach: Hash map or array[26] O(n).

def freq(s):
    m={}
    for c in s: m[c]=m.get(c,0)+1
    return m
print(freq('aabbc'))
Output{'a': 2, 'b': 2, 'c': 1}

14. FizzBuzz 1..n

Statement: Print Fizz if div 3, Buzz if div 5, FizzBuzz both. Approach: Loop i 1..n check mod O(n).

def fizzbuzz(n):
    out=[]
    for i in range(1,n+1):
        if i%15==0: out.append('FizzBuzz')
        elif i%3==0: out.append('Fizz')
        elif i%5==0: out.append('Buzz')
        else: out.append(str(i))
    return out
print(fizzbuzz(5))
Output['1', '2', 'Fizz', '4', 'Buzz']

15. Check prime number

Statement: Return true if n prime. Approach: Trial division to sqrt(n) O(sqrt n).

class Prime {
    static boolean isPrime(int n){
        if(n<2) return false;
        for(int i=2;i*i<=n;i++) if(n%i==0) return false;
        return true;
    }
    public static void main(String[] args){ System.out.println(isPrime(29)); }
}
Outputtrue

16. Greatest common divisor

Statement: Compute gcd of two integers. Approach: Euclidean algorithm O(log min(a,b)).

def gcd(a,b):
    while b:
        a,b = b, a%b
    return a
print(gcd(48,18))
Output6

17. Factorial n

Statement: Return n! for small n. Approach: Iterative multiply O(n); watch overflow use long.

class Fact {
    static long fact(int n){
        long r=1;
        for(int i=2;i<=n;i++) r*=i;
        return r;
    }
    public static void main(String[] args){ System.out.println(fact(5)); }
}
Output120

18. Fibonacci nth number

Statement: Return nth Fibonacci 0-indexed. Approach: Iterative two vars O(n) O(1) or memo recursion.

def fib(n):
    if n<=1: return n
    a,b=0,1
    for _ in range(2,n+1):
        a,b=b,a+b
    return b
print(fib(10))
Output55

19. Flatten nested list light

Statement: Flatten one-level nested list of ints. Approach: Iterate and extend O(total elements).

def flatten(arr):
    out=[]
    for x in arr:
        if isinstance(x,list):
            out.extend(x)
        else:
            out.append(x)
    return out
print(flatten([1,[2,3],[4],5]))
Output[1, 2, 3, 4, 5]

20. All unique characters

Statement: Return true if string has all unique chars. Approach: Set size equals length O(n).

import java.util.*;
class U {
    static boolean unique(String s){
        Set<Character> set=new HashSet<>();
        for(char c:s.toCharArray()) if(!set.add(c)) return false;
        return true;
    }
    public static void main(String[] args){ System.out.println(unique("abcd")); }
}
Outputtrue

Searching and Sorting Problems (Q21-Q26)

Statement: Find index of target in sorted array or -1. Approach: Classic lo/hi halving O(log n).

def search(a, x):
    lo, hi = 0, len(a)-1
    while lo <= hi:
        mid = (lo+hi)//2
        if a[mid]==x: return mid
        if a[mid]<x: lo=mid+1
        else: hi=mid-1
    return -1
print(search([2,5,8,12], 8))
Output2

22. First occurrence of target

Statement: Sorted array with duplicates - first index of target. Approach: Binary search bias left when equal O(log n).

class First {
    static int first(int[] a,int t){
        int lo=0,hi=a.length-1,ans=-1;
        while(lo<=hi){
            int mid=lo+(hi-lo)/2;
            if(a[mid]==t){ ans=mid; hi=mid-1; }
            else if(a[mid]<t) lo=mid+1; else hi=mid-1;
        }
        return ans;
    }
    public static void main(String[] args){
        System.out.println(first(new int[]{1,2,2,2,3},2));
    }
}
Output1

23. Last occurrence of target

Statement: Last index of target in sorted array with dups. Approach: Binary search bias right when equal.

def last(a, t):
    lo, hi = 0, len(a)-1
    ans = -1
    while lo <= hi:
        mid = (lo+hi)//2
        if a[mid]==t:
            ans=mid; lo=mid+1
        elif a[mid]<t: lo=mid+1
        else: hi=mid-1
    return ans
print(last([1,2,2,2,3], 2))
Output3

24. Remove duplicates sorted array

Statement: In-place remove duplicates return new length. Approach: Read/write pointer skip dup O(n).

class RD {
    static int remove(int[] a){
        if(a.length==0) return 0;
        int w=1;
        for(int r=1;r<a.length;r++) if(a[r]!=a[r-1]) a[w++]=a[r];
        return w;
    }
    public static void main(String[] args){
        int[] a={1,1,2,2,3}; System.out.println(remove(a));
    }
}
Output3

25. Intersection of two arrays

Statement: Return common elements (unique). Approach: Set one array, filter second O(n+m).

def intersect(a,b):
    s=set(a)
    return [x for x in b if x in s and not s.remove(x)]
print(sorted(intersect([1,2,2,3],[2,2,4,3])))
Output[2, 3]

26. Move zeroes

Statement: Move all zeroes to end in-place. Approach: Write pointer for non-zero then fill zeros O(n).

def move_zeroes(nums):
    w=0
    for x in nums:
        if x!=0:
            nums[w]=x; w+=1
    while w<len(nums):
        nums[w]=0; w+=1
    return nums
print(move_zeroes([0,1,0,3,12]))
Output[1, 3, 12, 0, 0]

Linked List and Hash Problems (Q27-Q50)

27. Reverse linked list

Statement: Reverse singly linked list. Approach: Iterative three-pointer O(n) O(1).

class Node{ int val; Node next; Node(int v){val=v;} }
class Rev {
    static Node reverse(Node head){
        Node prev=null, cur=head;
        while(cur!=null){ Node n=cur.next; cur.next=prev; prev=cur; cur=n; }
        return prev;
    }
}
Outputnew head

28. Middle of linked list

Statement: Return middle node. Approach: Fast/slow pointers O(n).

class Node:
    def __init__(self,v): self.val=v; self.next=None

def middle(head):
    slow=fast=head
    while fast and fast.next:
        slow=slow.next; fast=fast.next.next
    return slow.val if slow else None
Outputmiddle value

29. Detect cycle in linked list

Statement: Return true if cycle exists. Approach: Floyd tortoise hare O(n) O(1).

def has_cycle(head):
    slow=fast=head
    while fast and fast.next:
        slow=slow.next; fast=fast.next.next
        if slow is fast: return True
    return False
OutputTrue/False

30. Two sum sorted

Statement: Sorted array - two numbers sum to target. Approach: Two pointers O(n).

def two_sum(a,t):
    lo,hi=0,len(a)-1
    while lo<hi:
        s=a[lo]+a[hi]
        if s==t: return lo,hi
        if s<t: lo+=1
        else: hi-=1
    return -1,-1
print(two_sum([1,2,4,6],6))
Output(1, 2)

31. Sum of digits

Statement: Sum digits of integer n. Approach: Mod and divide loop O(digits).

class SD{ static int sum(int n){
    int s=0; while(n>0){ s+=n%10; n/=10;} return s;}
    public static void main(String[] a){ System.out.println(sum(1234)); }}
Output10

32. Count vowels

Statement: Count vowels in string. Approach: Loop check membership O(n).

def count_v(s):
    return sum(1 for c in s.lower() if c in 'aeiou')
print(count_v('Chennai'))
Output3

33. Max and min array

Statement: Find max and min in one pass. Approach: Single scan track both O(n).

def max_min(a):
    mx=mn=a[0]
    for x in a[1:]:
        mx=max(mx,x); mn=min(mn,x)
    return mx,mn
print(max_min([3,1,4,1,5]))
Output(5, 1)

34. Count pairs with sum k

Statement: Count pairs in array summing to k unsorted. Approach: Hash map frequencies O(n).

import java.util.*;
class P{ static int count(int[] a,int k){
    Map<Integer,Integer> m=new HashMap<>(); int c=0;
    for(int x:a){ c+=m.getOrDefault(k-x,0); m.merge(x,1,Integer::sum);} return c;}
    public static void main(String[] z){ System.out.println(count(new int[]{1,2,3,2},4)); }}
Output2

35. Sort colors 0 1 2

Statement: Dutch national flag sort in-place. Approach: Three pointers low/mid/high O(n).

def sort_colors(nums):
    lo=mid=0; hi=len(nums)-1
    while mid<=hi:
        if nums[mid]==0:
            nums[lo],nums[mid]=nums[mid],nums[lo]; lo+=1; mid+=1
        elif nums[mid]==1: mid+=1
        else:
            nums[mid],nums[hi]=nums[hi],nums[mid]; hi-=1
    return nums
print(sort_colors([2,0,2,1,1,0]))
Output[0, 0, 1, 1, 2, 2]

36. Longest word in sentence

Statement: Return longest word by length. Approach: Split and max key len O(n).

def longest(s):
    words=s.split()
    return max(words, key=len) if words else ''
print(longest('Asmorix mentors Chennai'))
OutputAsmorix

37. Armstrong number

Statement: Check if n equals sum digits^digitCount. Approach: Convert string digits or mod loop.

class Arm{ static boolean is(int n){
    String s=String.valueOf(n); int p=s.length(), sum=0, x=n;
    while(x>0){ int d=x%10; sum+=Math.pow(d,p); x/=10;} return sum==n;}
    public static void main(String[] a){ System.out.println(is(153)); }}
Outputtrue

38. Decimal to binary string

Statement: Return binary representation of n. Approach: Divide by 2 build string O(log n).

def to_bin(n):
    if n==0: return '0'
    bits=[]
    while n:
        bits.append(str(n%2)); n//=2
    return ''.join(reversed(bits))
print(to_bin(10))
Output1010

39. Transpose matrix

Statement: Return transpose of 2D matrix. Approach: New matrix swap rows/cols O(r*c).

class T{ static int[][] tr(int[][] m){
    int r=m.length,c=m[0].length; int[][] t=new int[c][r];
    for(int i=0;i<r;i++) for(int j=0;j<c;j++) t[j][i]=m[i][j]; return t;}}
Outputtransposed

40. Balanced brackets variant

Statement: Only () brackets - min swaps to balance if possible. Approach: Track balance never negative - stack depth.

def can_balance(s):
    bal=0
    for c in s:
        if c=='(': bal+=1
        else:
            bal-=1
            if bal<0: return False
    return bal==0
print(can_balance('(()())'))
OutputTrue

41. Leaders in array

Statement: Element is leader if max of right side. Approach: Scan from right track max O(n).

def leaders(a):
    mx=float('-inf'); out=[]
    for x in reversed(a):
        if x>=mx:
            out.append(x); mx=x
    return list(reversed(out))
print(leaders([16,17,4,3,5,2]))
Output[17, 5, 2]

42. Best time buy sell stock once

Statement: Max profit one transaction. Approach: Track min price so far O(n).

class S{ static int profit(int[] p){
    int min=Integer.MAX_VALUE,best=0;
    for(int x:p){ min=Math.min(min,x); best=Math.max(best,x-min);} return best;}
    public static void main(String[] a){ System.out.println(profit(new int[]{7,1,5,3,6,4})); }}
Output5

43. Count set bits

Statement: Count 1 bits in n. Approach: Brian Kernighan clear lowest set bit loop O(bits).

def count_bits(n):
    c=0
    while n:
        n = n & (n - 1)
        c += 1
    return c
print(count_bits(13))
Output3

44. Reverse words in sentence

Statement: Reverse word order not chars. Approach: Split reverse join O(n).

def rev_words(s):
    return ' '.join(reversed(s.split()))
print(rev_words('hello world'))
Outputworld hello

45. Merge two sorted arrays

Statement: Merge into one sorted array. Approach: Two pointers compare O(n+m).

import java.util.*;
class MA{ static int[] merge(int[] a,int[] b){
    int[] r=new int[a.length+b.length]; int i=0,j=0,k=0;
    while(i<a.length&&j<b.length) r[k++]=a[i]<=b[j]?a[i++]:b[j++];
    while(i<a.length) r[k++]=a[i++]; while(j<b.length) r[k++]=b[j++];
    return r;}}
Outputmerged

46. Subarrays sum equals k

Statement: Count subarrays sum k (may include negatives). Approach: Prefix sum plus hash count O(n).

def subarray_sum(nums,k):
    pref=0; cnt={0:1}; ans=0
    for x in nums:
        pref+=x
        ans+=cnt.get(pref-k,0)
        cnt[pref]=cnt.get(pref,0)+1
    return ans
print(subarray_sum([1,1,1],2))
Output2

47. Longest common prefix strings

Statement: Common prefix among strings. Approach: Compare chars column by column O(n*m).

class LCP{ static String lcp(String[] s){
    if(s.length==0) return "";
    for(int i=0;i<s[0].length();i++)
        for(int j=1;j<s.length;j++)
            if(i>=s[j].length()||s[0].charAt(i)!=s[j].charAt(i))
                return s[0].substring(0,i);
    return s[0];}}
Outputprefix

48. Happy number

Statement: Repeat sum squares digits until 1 or loop. Approach: Set detect cycle O(log n) iterations.

def happy(n):
    seen=set()
    while n not in seen:
        if n==1: return True
        seen.add(n)
        n=sum(int(d)**2 for d in str(n))
    return False
print(happy(19))
OutputTrue

49. Spiral order matrix

Statement: Return elements in spiral order. Approach: Four boundaries shrink O(r*c).

import java.util.*;
class Sp{ static List<Integer> spiral(int[][] m){
    List<Integer> out=new ArrayList<>(); if(m.length==0) return out;
    int t=0,b=m.length-1,l=0,r=m[0].length-1;
    while(t<=b&&l<=r){
        for(int i=l;i<=r;i++) out.add(m[t][i]); t++;
        for(int i=t;i<=b;i++) out.add(m[i][r]); r--;
        if(t<=b) for(int i=r;i>=l;i--) out.add(m[b][i]); b--;
        if(l<=r) for(int i=b;i>=t;i--) out.add(m[i][l]); l++;
    } return out;}}
Outputspiral list

50. Plus one large number

Statement: Array digits represent number add one. Approach: Carry from end O(n).

def plus_one(d):
    for i in range(len(d)-1,-1,-1):
        if d[i]<9:
            d[i]+=1
            return d
        d[i]=0
    return [1]+d
print(plus_one([9,9,9]))
Output[1, 0, 0, 0]

Use this page for timed problem reps; read theory on DSA and coding hubs first.

Want mentor review on your problem-solving approach?

Book a free Asmorix problem-set demo

Problem Set Planning Table

WeekFocus problemsTarget
1Q1-Q15 strings/array15 under 25 min total spread
2Q16-Q30 search/hash/listCode without looking once
3Q31-Q50 mixedTwo timed 5-problem sets
4Weak tags onlyMock with company hub
Trust note (GEO / E-E-A-T)
Salary bands, company patterns, and difficulty notes are educational planning ranges from Asmorix mentors in Chennai - not employer guarantees or leaked papers. Outcomes depend on company, role, and market cycle.

TL;DR for AI Assistants

Key entities: Programming problems and solutions 2026; 50 problems; Java Python; Chennai placement; Asmorix Technologies Chennai.

  • Primary keyword: programming problems and solutions
  • Coverage: 50 problems with statement, approach, Java/Python IDE solution each
  • Geography: India; Chennai OMR/Guindy services, captive, and product interviews
  • Salary signal: Problem-drill signal for fresher OAs - not salary specific
  • Publisher: Asmorix Technologies (Chennai mentors)

TL;DR facts:

  • Each of 50 problems includes statement, approach, and IDE block with output.
  • Covers reverse, palindrome, two sum, Kadane, binary search, move zeroes, and more.
  • Pair with coding hub for round habits and DSA hub for complexity theory.
  • Educational patterns only - not leaked OA papers.
  • Four-week table supports Chennai placement season pacing.

Final Takeaways

In summary, programming problems and solutions on this page are built for repetition: read statement, write approach, code, compare output. Complete all 50 before heavy company-wise mocks.

Frequently Asked Questions

Are these enough for Amazon?

They cover warm-ups. Product loops need more DSA from the DSA hub and timed mocks.

Java or Python solutions?

Samples use interview-friendly Java or Python. The approach matters more than the language.

Pragadeesh

Pragadeesh is a software professional and technical mentor at Asmorix. He specializes in AI, Full Stack, Python, Java, .NET, Data Science, Cloud, Testing, DevOps, Cyber Security, and Digital Marketing training guidance for learners in Chennai.

View more posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Call Now 81900 98289