Pseudocode for Algorithmic Problems
Problems on Arrays
Find the smallest number in an array
function findSmallest(arr, n) {
if n == 0 then
return error // or handle empty array
smallest = arr[0]
for i = 1 to n-1 {
if arr[i] < smallest then
smallest = arr[i]
}
return smallest
}
Find the largest number in an array
function findLargest(arr, n) {
if n == 0 then
return error
largest = arr[0]
for i = 1 to n-1 {
if arr[i] > largest then
largest = arr[i]
}
return largest
}
Second Smallest and Second Largest element in an array
function findSecondSmallestAndLargest(arr, n) {
if n < 2 then
return error // not enough elements
firstMin = secondMin = infinity
firstMax = secondMax = -infinity
for i = 0 to n-1 {
value = arr[i]
if value < firstMin then
1
secondMin = firstMin
firstMin = value
else if value < secondMin and value != firstMin then
secondMin = value
if value > firstMax then
secondMax = firstMax
firstMax = value
else if value > secondMax and value != firstMax then
secondMax = value
}
return secondMin, secondMax
}
Reverse a given array
function reverseArray(arr, n) {
left = 0
right = n-1
while left < right {
swap(arr[left], arr[right])
left = left + 1
right = right - 1
}
// now arr is reversed
}
Count frequency of each element in an array
function countFrequency(arr, n) {
create an empty map freq
for i = 0 to n-1 {
if arr[i] exists in freq then
freq[arr[i]] = freq[arr[i]] + 1
else
freq[arr[i]] = 1
}
return freq
}
Rearrange array in increasing-decreasing order
function rearrangeIncDec(arr, n) {
sort(arr, n) // sort in ascending order
create new array result of size n
2
left = 0, right = n-1, idx = 0
while left <= right {
if idx % 2 == 0 then
result[idx] = arr[left]
left = left + 1
else
result[idx] = arr[right]
right = right - 1
idx = idx + 1
}
// copy result back to arr if needed
return result
}
Calculate sum of the elements of the array
function sumArray(arr, n) {
sum = 0
for i = 0 to n-1 {
sum = sum + arr[i]
}
return sum
}
Rotate array by K elements (Block Swap Algorithm)
function leftRotate(arr, d, n) {
if d == 0 or d == n then
return // no rotation needed
blockSwap(arr, 0, d, n)
}
function blockSwap(arr, start, d, n) {
len = n - start
if d == len or d == 0 then
return
if d < len - d then
// swap A (start...start+d-1) with last part of length d
for i = 0 to d-1 {
swap(arr[start + i], arr[start + len - d + i])
}
blockSwap(arr, start, d, n - d)
else if d > len - d then
// swap first len-d elements with B (start+len-d...start+len-1)
for i = 0 to len - d - 1 {
3
swap(arr[start + i], arr[start + d + i])
}
blockSwap(arr, start + len - d, d - (len - d), n)
else
// d == len - d, swap A and B
for i = 0 to d-1 {
swap(arr[start + i], arr[start + d + i])
}
return
}
Average of all elements in an array
function averageArray(arr, n) {
if n == 0 then
return 0 // or error
total = sumArray(arr, n)
return total / n
}
Find the median of the given array
function findMedian(arr, n) {
sort(arr, n)
if n is odd then
return arr[n/2]
else
mid1 = arr[(n/2) - 1]
mid2 = arr[n/2]
return (mid1 + mid2) / 2
}
Remove duplicates from a sorted array
function removeDuplicatesSorted(arr, n) {
if n == 0 or n == 1 then
return n
index = 0
for i = 1 to n-1 {
if arr[i] != arr[index] then
index = index + 1
arr[index] = arr[i]
}
// unique elements are from 0 to index
4
return index + 1
}
Remove duplicates from unsorted array
function removeDuplicatesUnsorted(arr, n) {
create empty map seen
create new array result
for i = 0 to n-1 {
if arr[i] not in seen then
result.append(arr[i])
seen[arr[i]] = true
}
return result
}
Adding Element in an array
function insertElement(arr, n, element, pos) {
if pos < 0 or pos > n then
return error
// shift elements to make space
for i = n down to pos+1 {
arr[i] = arr[i-1]
}
arr[pos] = element
n = n + 1
return n // new size
}
Find all repeating elements in an array
function findRepeating(arr, n) {
create map freq
for i = 0 to n-1 {
freq[arr[i]] = freq.get(arr[i], 0) + 1
}
for each element in freq {
if freq[element] > 1 then
print element
}
}
5
Find all non-repeating elements in an array
function findNonRepeating(arr, n) {
create map freq
for i = 0 to n-1 {
freq[arr[i]] = freq.get(arr[i], 0) + 1
}
for each element in freq {
if freq[element] == 1 then
print element
}
}
Find all symmetric pairs in array
// Assumes array of pairs (pairs[i] = (x, y))
function findSymmetricPairs(pairs, n) {
create map pairMap
for i = 0 to n-1 {
(x, y) = pairs[i]
if pairMap contains (y, x) then
print (x, y)
else
pairMap[(x, y)] = true
}
}
Maximum product subarray in an array
function maxProductSubarray(arr, n) {
maxProd = arr[0]
minProd = arr[0]
result = arr[0]
for i = 1 to n-1 {
if arr[i] < 0 then
swap(maxProd, minProd)
maxProd = max(arr[i], maxProd * arr[i])
minProd = min(arr[i], minProd * arr[i])
result = max(result, maxProd)
}
return result
}
6
Replace each element of the array by its rank in the array
function replaceWithRank(arr, n) {
copy = arr copy
sort(copy, n)
create map rank
rank[copy[0]] = 1
currentRank = 1
for i = 1 to n-1 {
if copy[i] != copy[i-1] then
currentRank = currentRank + 1
rank[copy[i]] = currentRank
}
for i = 0 to n-1 {
arr[i] = rank[arr[i]]
}
}
Sorting elements of an array by frequency
function sortByFrequency(arr, n) {
create map freq
for i = 0 to n-1 {
freq[arr[i]] = freq.get(arr[i], 0) + 1
}
create list of (element, freq) pairs from freq
sort list by frequency ascending (or descending)
create result list
for each (element, f) in sorted list {
for j = 1 to f {
result.append(element)
}
}
return result
}
Rotation of elements of array (left and right)
function leftRotateOne(arr, n) {
first = arr[0]
for i = 0 to n-2 {
arr[i] = arr[i+1]
}
arr[n-1] = first
7
}
function rightRotateOne(arr, n) {
last = arr[n-1]
for i = n-1 down to 1 {
arr[i] = arr[i-1]
}
arr[0] = last
}
Finding equilibrium index of an array
function findEquilibrium(arr, n) {
totalSum = sumArray(arr, n)
leftSum = 0
for i = 0 to n-1 {
totalSum = totalSum - arr[i]
if leftSum == totalSum then
print i
leftSum = leftSum + arr[i]
}
}
Finding Circular rotation of an array by K positions
// This can be same as left rotation by K
function circularRotate(arr, k, n) {
leftRotate(arr, k, n)
}
Sort an array according to the order defined by another array
function sortByAnotherArray(arr1, n, arr2, m) {
create map order
for i = 0 to m-1 {
order[arr2[i]] = i
}
sort arr1 with custom comparator:
if both arr1[x] and arr1[y] in order then
compare order[arr1[x]] and order[arr1[y]]
else if arr1[x] in order then
arr1[x] goes before arr1[y]
else if arr1[y] in order then
arr1[y] goes before arr1[x]
8
else
compare arr1[x] and arr1[y] normally
return arr1
}
Search an element in an array
function searchElement(arr, n, x) {
for i = 0 to n-1 {
if arr[i] == x then
return i // index found
}
return -1 // not found
}
Check if Array is a subset of another array or not
function isSubset(arr1, n1, arr2, n2) {
create set s
for i = 0 to n2-1 {
s.add(arr2[i])
}
for i = 0 to n1-1 {
if arr1[i] not in s then
return false
}
return true
}
Problems on Numbers
Check if a number is palindrome or not
function isNumberPalindrome(n) {
original = n
reverse = 0
while n > 0 {
digit = n % 10
reverse = reverse * 10 + digit
n = n / 10
}
if original == reverse then
return true
else
9
return false
}
Find all Palindrome numbers in a given range
function palindromeInRange(start, end) {
for num = start to end {
if isNumberPalindrome(num) then
print num
}
}
Check if a number is prime or not
function isPrime(n) {
if n <= 1 then
return false
for i = 2 to sqrt(n) {
if n % i == 0 then
return false
}
return true
}
Prime numbers in a given range
function primesInRange(start, end) {
for num = start to end {
if isPrime(num) then
print num
}
}
Check if a number is Armstrong number or not
function isArmstrong(n) {
original = n
sum = 0
digits = numberOfDigits(n)
while n > 0 {
digit = n % 10
sum = sum + power(digit, digits)
n = n / 10
10
}
return (sum == original)
}
Check if a number is perfect number
function isPerfect(n) {
if n <= 1 then
return false
sum = 1
for i = 2 to n/2 {
if n % i == 0 then
sum = sum + i
}
return (sum == n)
}
Even or Odd
function checkEvenOdd(n) {
if n % 2 == 0 then
print "Even"
else
print "Odd"
}
Check whether a given number is positive or negative
function checkSign(n) {
if n > 0 then
print "Positive"
else if n < 0 then
print "Negative"
else
print "Zero"
}
Sum of first N natural numbers
function sumNatural(N) {
sum = 0
for i = 1 to N {
sum = sum + i
11
}
return sum
}
Find Sum of AP Series
// Sum of AP: a + (a+d) + ... for n terms
function sumAP(a, d, n) {
sum = 0
term = a
for i = 1 to n {
sum = sum + term
term = term + d
}
return sum
}
Program to find sum of GP Series
// Sum of GP: a + ar + ar^2 + ... for n terms
function sumGP(a, r, n) {
sum = 0
term = a
for i = 1 to n {
sum = sum + term
term = term * r
}
return sum
}
Greatest of two numbers
function maxOfTwo(a, b) {
if a > b then
return a
else
return b
}
Greatest of three numbers
function maxOfThree(a, b, c) {
max = a
12
if b > max then
max = b
if c > max then
max = c
return max
}
Leap Year or not
function isLeapYear(year) {
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0) then
return true
else
return false
}
Reverse digits of a number
function reverseDigits(n) {
reverse = 0
while n > 0 {
reverse = reverse * 10 + n % 10
n = n / 10
}
return reverse
}
Maximum and Minimum digit in a number
function maxMinDigit(n) {
minDigit = 9
maxDigit = 0
while n > 0 {
digit = n % 10
if digit < minDigit then
minDigit = digit
if digit > maxDigit then
maxDigit = digit
n = n / 10
}
return minDigit, maxDigit
}
13
Print Fibonacci up to Nth Term
function printFibonacci(N) {
if N >= 1 then
print 0
if N >= 2 then
print 1
a = 0
b = 1
for i = 3 to N {
fib = a + b
print fib
a = b
b = fib
}
}
Factorial of a number
function factorial(n) {
result = 1
for i = 1 to n {
result = result * i
}
return result
}
Power of a number
function power(base, exp) {
result = 1
for i = 1 to exp {
result = result * base
}
return result
}
Factors of a given number
function printFactors(n) {
for i = 1 to n {
if n % i == 0 then
print i
14
}
}
Print all prime factors of the given number
function printPrimeFactors(n) {
while n % 2 == 0 {
print 2
n = n / 2
}
for i = 3 to sqrt(n) step 2 {
while n % i == 0 {
print i
n = n / i
}
}
if n > 2 then
print n
}
Check if a number is a strong number or not
function isStrongNumber(n) {
original = n
sum = 0
while n > 0 {
digit = n % 10
sum = sum + factorial(digit)
n = n / 10
}
return (sum == original)
}
Check if a Number is Automorphic
function isAutomorphic(n) {
square = n * n
digits = numberOfDigits(n)
if square % (10^digits) == n then
return true
else
return false
}
15
GCD of two numbers
function gcd(a, b) {
if b == 0 then
return a
else
return gcd(b, a % b)
}
LCM of two numbers
function lcm(a, b) {
return (a * b) / gcd(a, b)
}
Check if a number is Harshad number
function isHarshad(n) {
sum = 0
temp = n
while temp > 0 {
sum = sum + temp % 10
temp = temp / 10
}
return (n % sum == 0)
}
Check if the number is abundant number or not
function isAbundant(n) {
sum = 1
for i = 2 to n/2 {
if n % i == 0 then
sum = sum + i
}
return (sum > n)
}
Sum of digits of a number
function sumOfDigits(n) {
sum = 0
16
while n > 0 {
sum = sum + n % 10
n = n / 10
}
return sum
}
Sum of numbers in the given range
function sumRange(start, end) {
total = 0
for i = start to end {
total = total + i
}
return total
}
Permutations in which N people can occupy R seats in a classroom
// nPr = n! / (n-r)!
function permutations(n, r) {
return factorial(n) / factorial(n - r)
}
Program to add two fractions
function addFractions(a, b, c, d) {
// a/b + c/d
num = a * d + b * c
den = b * d
g = gcd(num, den)
num = num / g
den = den / g
return num + "/" + den
}
Replace all 0s with 1s in a given integer
function replaceZeros(n) {
result = 0
place = 1
while n > 0 {
digit = n % 10
17
if digit == 0 then
digit = 1
result = result + digit * place
place = place * 10
n = n / 10
}
return result
}
Can a number be expressed as a sum of two prime numbers
function isSumOfTwoPrimes(n) {
for i = 2 to n/2 {
if isPrime(i) and isPrime(n - i) then
print i, (n - i)
break
}
}
Calculate the area of circle
function areaOfCircle(r) {
return PI * r * r
}
Program to find roots of a Quadratic Equation
function findRoots(a, b, c) {
disc = b * b - 4 * a * c
if disc > 0 then
root1 = (-b + sqrt(disc)) / (2 * a)
root2 = (-b - sqrt(disc)) / (2 * a)
return root1, root2
else if disc == 0 then
root = -b / (2 * a)
return root
else
// complex roots
real = -b / (2 * a)
imag = sqrt(-disc) / (2 * a)
return real + "+" + imag + "i", real + "-" + imag + "i"
}
18
Problems on Number System
Convert Binary to Decimal
function binaryToDecimal(bin) {
dec = 0
base = 1
while bin > 0 {
dec = dec + (bin % 10) * base
base = base * 2
bin = bin / 10
}
return dec
}
Convert Binary to Octal
function binaryToOctal(bin) {
dec = binaryToDecimal(bin)
oct = 0
place = 1
while dec > 0 {
oct = oct + (dec % 8) * place
dec = dec / 8
place = place * 10
}
return oct
}
Decimal to Binary conversion
function decimalToBinary(dec) {
bin = 0
place = 1
while dec > 0 {
bin = bin + (dec % 2) * place
dec = dec / 2
place = place * 10
}
return bin
}
19
Convert Decimal to Octal
function decimalToOctal(dec) {
oct = 0
place = 1
while dec > 0 {
oct = oct + (dec % 8) * place
dec = dec / 8
place = place * 10
}
return oct
}
Convert Octal to Binary
function octalToBinary(oct) {
dec = octalToDecimal(oct)
return decimalToBinary(dec)
}
Convert Octal to Decimal
function octalToDecimal(oct) {
dec = 0
base = 1
while oct > 0 {
dec = dec + (oct % 10) * base
base = base * 8
oct = oct / 10
}
return dec
}
Convert digits/numbers to words
function numberToWords(n) {
if n == 0 then
print "zero"
digits = empty list
while n > 0 {
digits.prepend(n % 10)
n = n / 10
}
20
for each digit in digits {
print wordMap[digit] // e.g., 0->"zero", 1->"one", etc.
}
}
Problems on Sorting
Bubble Sort Algorithm
function bubbleSort(arr, n) {
for i = 0 to n-2 {
for j = 0 to n-2-i {
if arr[j] > arr[j+1] then
swap(arr[j], arr[j+1])
}
}
}
Selection Sort Algorithm
function selectionSort(arr, n) {
for i = 0 to n-2 {
minIndex = i
for j = i+1 to n-1 {
if arr[j] < arr[minIndex] then
minIndex = j
}
swap(arr[i], arr[minIndex])
}
}
Insertion Sort Algorithm
function insertionSort(arr, n) {
for i = 1 to n-1 {
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key {
arr[j+1] = arr[j]
j = j - 1
}
arr[j+1] = key
21
}
}
Quick Sort Algorithm
function quickSort(arr, low, high) {
if low < high then
pi = partition(arr, low, high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
}
function partition(arr, low, high) {
pivot = arr[high]
i = low - 1
for j = low to high-1 {
if arr[j] < pivot then
i = i + 1
swap(arr[i], arr[j])
}
swap(arr[i+1], arr[high])
return i+1
}
Merge Sort Algorithm
function mergeSort(arr, l, r) {
if l < r then
m = (l + r) / 2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
}
function merge(arr, l, m, r) {
// create left and right subarrays
leftSize = m - l + 1
rightSize = r - m
left[leftSize], right[rightSize]
for i = 0 to leftSize-1 {
left[i] = arr[l + i]
}
for j = 0 to rightSize-1 {
right[j] = arr[m + 1 + j]
}
22
i = 0, j = 0, k = l
while i < leftSize and j < rightSize {
if left[i] <= right[j] then
arr[k] = left[i]
i = i + 1
else
arr[k] = right[j]
j = j + 1
k = k + 1
}
while i < leftSize {
arr[k] = left[i]
i = i + 1
k = k + 1
}
while j < rightSize {
arr[k] = right[j]
j = j + 1
k = k + 1
}
}
Problems on Strings
Check if a given string is palindrome or not
function isStringPalindrome(s) {
i = 0, j = length(s) - 1
while i < j {
if s[i] != s[j] then
return false
i = i + 1
j = j - 1
}
return true
}
Count number of vowels, consonants, spaces in String
function countVowelsConsonantsSpaces(s) {
vowels = 0, consonants = 0, spaces = 0
for each char in s {
if char is vowel then
vowels = vowels + 1
else if char is alphabet then
23
consonants = consonants + 1
else if char is space then
spaces = spaces + 1
}
print vowels, consonants, spaces
}
Find the ASCII value of a character
function asciiValue(c) {
return (int) c
}
Remove all vowels from the string
function removeVowels(s) {
result = ""
for each char in s {
if char not in [a, e, i, o, u, A, E, I, O, U] then
result = result + char
}
return result
}
Remove spaces from a string
function removeSpaces(s) {
result = ""
for each char in s {
if char != ' ' then
result = result + char
}
return result
}
Remove characters from a string except alphabets
function keepAlphabets(s) {
result = ""
for each char in s {
if char is alphabet then
result = result + char
}
24
return result
}
Reverse a String
function reverseString(s) {
result = ""
for i = length(s)-1 down to 0 {
result = result + s[i]
}
return result
}
Remove brackets from an algebraic expression
function removeBrackets(expr) {
result = ""
for each char in expr {
if char != '(' and char != ')' then
result = result + char
}
return result
}
Sum of the numbers in a String
function sumNumbersInString(s) {
sum = 0
temp = ""
for each char in s {
if char is digit then
temp = temp + char
else
if temp != "" then
sum = sum + toInteger(temp)
temp = ""
}
if temp != "" then
sum = sum + toInteger(temp)
return sum
}
25
Capitalize first and last character of each word
function capitalizeFirstLast(s) {
words = split(s, " ")
for each word in words {
if length(word) > 0 then
word[0] = toUpper(word[0])
if length(word) > 1 then
word[length(word)-1] = toUpper(word[length(word)-1])
}
result = join(words, " ")
return result
}
Calculate frequency of characters in a string
function charFrequency(s) {
create map freq
for each char in s {
freq[char] = freq.get(char, 0) + 1
}
return freq
}
Find Non-repeating characters of a String
function nonRepeatingChars(s) {
freq = charFrequency(s)
for char in s {
if freq[char] == 1 then
print char
}
}
Check if two strings are anagram of each other
function areAnagrams(s1, s2) {
if length(s1) != length(s2) then
return false
sort(s1)
sort(s2)
return (s1 == s2)
}
26
Count common sub-sequence in two strings
// Typically refers to longest common subsequence length
function longestCommonSubsequence(s1, s2) {
m = length(s1), n = length(s2)
create 2D array L[m+1][n+1]
for i = 0 to m {
for j = 0 to n {
if i == 0 or j == 0 then
L[i][j] = 0
else if s1[i-1] == s2[j-1] then
L[i][j] = L[i-1][j-1] + 1
else
L[i][j] = max(L[i-1][j], L[i][j-1])
}
}
return L[m][n] // length of LCS
}
Check if two strings match where one string contains wildcard characters
// Assume wildcard '*' matches any sequence, '?' matches any single char
function wildcardMatch(s, pat) {
if pat is empty then
return (s is empty)
if pat[0] == '*' then
// match zero or more characters
return wildcardMatch(s, pat[1:]) or (s not empty and
wildcardMatch(s[1:], pat))
else if pat[0] == '?' or pat[0] == s[0] then
return wildcardMatch(s[1:], pat[1:])
else
return false
}
Return maximum occurring character in the input string
function maxOccurringChar(s) {
freq = charFrequency(s)
maxCount = 0
maxChar = ''
for char, count in freq {
if count > maxCount then
maxCount = count
27
maxChar = char
}
return maxChar
}
Remove all duplicates from the input string
function removeDuplicatesString(s) {
seen = set()
result = ""
for char in s {
if char not in seen then
result = result + char
seen.add(char)
}
return result
}
Print all the duplicates in the input string
function printDuplicatesString(s) {
freq = charFrequency(s)
for char, count in freq {
if count > 1 then
print char
}
}
Remove characters from first string present in the second string
function removeCharsFromFirst(s1, s2) {
setChars = set(chars of s2)
result = ""
for char in s1 {
if char not in setChars then
result = result + char
}
return result
}
28
Change every letter with the next lexicographic alphabet in the given string
function nextAlphabet(s) {
result = ""
for char in s {
if char == 'z' then
result = result + 'a'
else if char == 'Z' then
result = result + 'A'
else
result = result + (char + 1) // move to next char
}
return result
}
Write a program to find the largest word in a given string
function largestWord(s) {
words = split(s, " ")
maxWord = ""
for each word in words {
if length(word) > length(maxWord) then
maxWord = word
}
return maxWord
}
Write a program to sort characters in a string
function sortString(s) {
chars = array of characters of s
sort(chars)
return join(chars)
}
Count number of words in a given string
function countWords(s) {
words = split(s, " ")
return length(words)
}
29
Write a program to find a word in a given string which has the highest number of
repeated letters
function wordWithMostRepeats(s) {
words = split(s, " ")
maxRepeatWord = ""
maxRepeatCount = 0
for each word in words {
freq = charFrequency(word)
localMax = 0
for char, count in freq {
if count > localMax then
localMax = count
}
if localMax > maxRepeatCount then
maxRepeatCount = localMax
maxRepeatWord = word
}
return maxRepeatWord
}
Change case of each character in a string
function changeCase(s) {
result = ""
for char in s {
if isUppercase(char) then
result = result + toLower(char)
else if isLowercase(char) then
result = result + toUpper(char)
else
result = result + char
}
return result
}
Concatenate one string to another
function concatenate(s1, s2) {
return s1 + s2
}
30
Write a program to find a substring within a string. If found display its starting
position
function findSubstring(s, sub) {
for i = 0 to length(s) - length(sub) {
if s[i : i+length(sub)] == sub then
return i
}
return -1 // not found
}
Reverse words in a string
function reverseWords(s) {
words = split(s, " ")
reverse(words)
return join(words, " ")
}
31