120+ Common Code and Interview Problems Solved in Python

Master the most common code and interview problems in Python with this comprehensive guide. Learn how to solve real-world programming problems with Python and ace your next interview.

Star History

Star History Chart

Updates

ProblemLink
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.adjacentElementProduct.py
Convert the string "123" into 123, without using the built-api int()atoi.py
Given an array , find if the number exists, develop a recursive implementation of the binary search. If the element is not found it returns -1binary_search_recursive.py
Bresenham Line Algorithm (BLA) is one of the earliest algorithms developed in computer graphics. It is used for drawing linesbresenham_line_algorithm.py
Find the no. of nodes in a BST that lies in a given rangebst_nodes_in_range.py
Bubble SortbubbleSort.py
Find the angle made by the hour hand and the minute hand at any given time. Assume it is an analog clockcalculateClockAngle.py
Two strings of sizes m and n are given, we have to find how many characters need to be removed from both the string so that they become anagrams of each othercheck_anagrams.py
Find the numbers which are semiprimes, within a given range. A semiprime is a product of two prime numbers, not necessarily distinct. Squares of prime numbers are also semiprimes.check_semiprime.py
Given a graph, there are two methods to perform traversal on it 1. Depth First Search (DFS) 2. Breadth First Search (BFS)dfs_bfs.py
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes(leftmost leaf node and rightmost leaf node).diameterOfTree.py
Estimate pi using random distributionestimate_pi.py
Write an efficient program for printing k largest elements in an array. Elements in array can be in any order.find_k_largest.py
Given a linked list, this method will return m'th element to the last 2->3->4->8->5; m=2 will return 8 since 8 is second to lastfind_m_to_last_llist.py
Given an array of numbers, find all the pairs of numbers which sum upto kfind_pairs_sum_k.py
Given an array of numbers, find all the pairs of numbers whose product is kfind_products_pair_k.py
Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a^2 + b^2 = c^2.find_pythagoras_triplet.py
Given a binary tree, find the second largest node in itfind_second_largest_in_binary_tree.py
Write a function that computes the list of the first 100 Fibonacci numbersfirst_n_fibo.py
Given an input string, it gives the first non repeating character in itfirst_non_repeating.py
Given an input string, find the first recurring character in it.first_recurring_character.py
Given a string, find the first non-repeating character in it. For example, if the input string is “GeeksforGeeks”, then output should be ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.first_unique_letter.py
Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021gen_largest_num_frm_list.py
Tree Data Structure in Pythongeneral_tree_structure.py
Given the arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits.

We are given two arrays that represent the arrival and departure times of trains that stop.
getMinPlatforms.py
Print duplicate characters in a stringget_dup_chars.py
Check if a given array has zero sum sub arrayhasZeroSumSubArray.py
Given a string, check if it only contains digitshas_only_digits.py
Given two lat, long coordinates , calculate Haversine distance between themhaversine.py
Heap Data Structureheap_structure.py
Print numbers 1 to 100 without using any numbers or integershundred_without_int.py
Write a program to convert interger to Roman Representationinterger_to_roman_num.py
Given two sorted array of sizes m and n in which all elements are distinct. Find the common elements between themintersection_arrays.py
Check if a matrix is symmetric or notisMatrixSymmetric.py
Check if two strings are anagrams of each otheris_anagram.py
Check if two strings are anagrams of each otheris_anagram_using_collections.py
Write a program to check if a number is a palindrome or notis_num_palindrome.py
Given a string, return True if it is a numeric data type, False otherwiseis_numeric.py
N soldiers are standing in a circle and first person has sword and he kills the 2nd person and gives the sword to the third person and so on till 99th person kills the 100th person gives the sword back to the first person, this goes on till only one person survives. Print the survivor.josephus.py
The effective time complexity of this improved version is O(logN). For the problem statement, refer josephus.pyjosephus_improved.py
The effective time complexity of this improved version is O(1). For the problem statement, refer josephus.pyjosephus_improved_v3.py
Implement the Karatsuba algorithmkaratsuba.py
Implement Level Order traversal for a binary treelevel_order_tree.py
Linked List Data Structurelinked_list_data_structure.py
Detect if a linked list has a looploop_in_linkedlist.py
Find the Lowest Common ancestor between two nodes in a binary search tree. Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).

The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root.
lowest_common_ancestor.py
A majority element in an array A[] of size n is an element that appears more than n/2 times. Find the majority element in the given array.majority_element.py
Find the max number in an array without using built-in functionsmax_in_array.py
Given a list of positive and negative numbers, find the maximum subarray sum. Constraint: Solve it in O(n)maximum_subarray_sum.py
Implementation of Merge Sortmerge_sort.py
Find the minimum and maximum numbers in an array in a single loopmin_max_array_oneLoop.py
Given an array of integers we need to move all the zeroes to the end and maintain the order of rest of the elements. Needless to say it should be an in-place solutionmove_zeros_to_end.py
Print the nodes of a binary tree which do not have a siblingno_sibling_tree.py
Let all odd numbers come before even numbers, and sort the odd numbers in ascending order and even numbers in descending order. For example, the string '1982376455' becomes '1355798642'oddAscEvenDesc.py
Compute and print the pascal traingle, given the no. of levelspascal_triangle.py
using factorial, reduced the time complexity of program from O(2^N) to O(N)pascals_triangle_improved.py
Print the permutations of a stringpermutations.py
Print the permutatations of a string (Simplified)permute_strings.py
Preorder Traversal of a Binary Search Tree in Iterative fashionpreorder_iterative_bst.py
Implementation of a priority Queuepriority_queue_simple.py
Process the string "k:1k1:2
Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i].product_puzzle.py
Implementation of a Queue Data Structurequeue_data_structure.py
Implementation of Quick Sortquick_sort.py
Write an efficient function that deletes characters from an ASCII string where any character existing in remove must be deleted from str. For example, given a str of "Battle of the Vowels: Hawaii vs. Grozny" and a remove of "aeiou", the function should transform str to “Bttl f th Vwls: Hw vs. Grzny”.remove_chars.py
Remove duplicate characters from stringremove_dup_chars.py
Remove duplicates using a dictionaryremove_duplicates.py
Remove duplicates using extra spaceremove_duplicates_v2.py
Reverse the string in placereverse_in_place.py
Reverse the string using recursionreverse_str_recursive.py
Given a sentence, reverse each word but don't reverse the sentencereverse_words.py
Given a matrix, rotate it by 180 degreerotateMatrix180Deg.py
Find Median from Data Stream of integersrunning_median_integers.py
Given a sorted array in which all elements appear twice (one after one) and one element appears only once. Find that element Constraints: in O(log n) complexity.search_unique.py
A simple implementation of Selection Sortselection_sort.py
A simple implementation of Stack Data Structurestack_data_structure.py
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.

Problem: We have a series of n daily price quotes for a stock and we need to calculate span of stock’s price for all n days
stock_span.py
Write a program to sum a given array using recursionsum_array_recursion.py
You are getting two streams of data with dates as key, merge the two streams and return average of the values if there is a common date else just update the value as received in the stream, refer example in the codetimeseries.py
Given two sorted array of sizes m and n in which all elements are distinct. Find the union between them Constraints: in O(m+n) complexity.union_arrays.py
Username validation programusername_validation.py
Given an array of integers(+ve,-ve and 0) find the sign of the product of all the given values.signOfProduct.py
  
  
  
  
  
  
  

Problems available: Solved -- 63 ; Newly Added -- 57

1. Code Style is added

2. 57 new problems are added in Interview_Questions.md. Solutions to be uploaded soon.

alt text 40+ Common code and interview problems solved in Python (it's growing...)

The core idea is not to utilize built-in functions or library and giving it a more logic-based approach, so that it can be language-friendly and not end up being another repository of "Python Tips and Tricks" .

How good is the code ?

  • It is well tested
  • Consistent formatting (using Black)
  • It can compile in its current state (and there are relatively no issues)

How much support is available?

  • FAQs (coming soon)
  • Documentation (coming soon)

Issues

Feel free to submit issues and enhancement requests.

Contributing

Please refer to each project's style guidelines and guidelines for submitting patches and additions. In general, we follow the "fork-and-pull" Git workflow.

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull request so that we can review your changes

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

LICENSE

MIT License


View on GitHub: https://github.com/devAmoghS/Python-Interview-Problems-for-Practice 

#python 

120+ Common Code and Interview Problems Solved in Python
31.65 GEEK