Pseudocode for Algorithmic Problems
Pseudocode for Algorithmic Problems
Problems on Arrays
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
}
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
}
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
}
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
}
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
}
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
}
function sumArray(arr, n) {
sum = 0
for i = 0 to n-1 {
sum = sum + arr[i]
}
return sum
}
function leftRotate(arr, d, n) {
if d == 0 or d == n then
return // no rotation needed
blockSwap(arr, 0, d, n)
}
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
}
function averageArray(arr, n) {
if n == 0 then
return 0 // or error
total = sumArray(arr, n)
return total / n
}
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
}
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
}
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
}
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
}
}
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]]
}
}
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
}
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
}
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]
}
}
8
else
compare arr1[x] and arr1[y] normally
return arr1
}
function searchElement(arr, n, x) {
for i = 0 to n-1 {
if arr[i] == x then
return i // index found
}
return -1 // not found
}
Problems on Numbers
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
}
function isPrime(n) {
if n <= 1 then
return false
for i = 2 to sqrt(n) {
if n % i == 0 then
return false
}
return true
}
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)
}
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"
}
function checkSign(n) {
if n > 0 then
print "Positive"
else if n < 0 then
print "Negative"
else
print "Zero"
}
function sumNatural(N) {
sum = 0
for i = 1 to N {
sum = sum + i
11
}
return sum
}
function maxOfTwo(a, b) {
if a > b then
return a
else
return b
}
function maxOfThree(a, b, c) {
max = a
12
if b > max then
max = b
if c > max then
max = c
return max
}
function isLeapYear(year) {
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0) then
return true
else
return false
}
function reverseDigits(n) {
reverse = 0
while n > 0 {
reverse = reverse * 10 + n % 10
n = n / 10
}
return reverse
}
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 printFactors(n) {
for i = 1 to n {
if n % i == 0 then
print i
14
}
}
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
}
function isStrongNumber(n) {
original = n
sum = 0
while n > 0 {
digit = n % 10
sum = sum + factorial(digit)
n = n / 10
}
return (sum == original)
}
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)
}
function lcm(a, b) {
return (a * b) / gcd(a, b)
}
function isHarshad(n) {
sum = 0
temp = n
while temp > 0 {
sum = sum + temp % 10
temp = temp / 10
}
return (n % sum == 0)
}
function isAbundant(n) {
sum = 1
for i = 2 to n/2 {
if n % i == 0 then
sum = sum + i
}
return (sum > n)
}
function sumOfDigits(n) {
sum = 0
16
while n > 0 {
sum = sum + n % 10
n = n / 10
}
return sum
}
// nPr = n! / (n-r)!
function permutations(n, r) {
return factorial(n) / factorial(n - r)
}
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
}
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
}
function isSumOfTwoPrimes(n) {
for i = 2 to n/2 {
if isPrime(i) and isPrime(n - i) then
print i, (n - i)
break
}
}
function areaOfCircle(r) {
return PI * r * r
}
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
function binaryToDecimal(bin) {
dec = 0
base = 1
while bin > 0 {
dec = dec + (bin % 10) * base
base = base * 2
bin = bin / 10
}
return dec
}
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
}
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
}
function octalToBinary(oct) {
dec = octalToDecimal(oct)
return decimalToBinary(dec)
}
function octalToDecimal(oct) {
dec = 0
base = 1
while oct > 0 {
dec = dec + (oct % 10) * base
base = base * 8
oct = oct / 10
}
return dec
}
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
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])
}
}
}
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])
}
}
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
}
}
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
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
}
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
}
function asciiValue(c) {
return (int) c
}
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
}
function removeSpaces(s) {
result = ""
for each char in s {
if char != ' ' then
result = result + char
}
return result
}
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
}
function removeBrackets(expr) {
result = ""
for each char in expr {
if char != '(' and char != ')' then
result = result + char
}
return result
}
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
}
function charFrequency(s) {
create map freq
for each char in s {
freq[char] = freq.get(char, 0) + 1
}
return freq
}
function nonRepeatingChars(s) {
freq = charFrequency(s)
for char in s {
if freq[char] == 1 then
print char
}
}
26
Count common sub-sequence in two strings
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
}
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
}
function removeDuplicatesString(s) {
seen = set()
result = ""
for char in s {
if char not in seen then
result = result + char
seen.add(char)
}
return result
}
function printDuplicatesString(s) {
freq = charFrequency(s)
for char, count in freq {
if count > 1 then
print char
}
}
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
}
function largestWord(s) {
words = split(s, " ")
maxWord = ""
for each word in words {
if length(word) > length(maxWord) then
maxWord = word
}
return maxWord
}
function sortString(s) {
chars = array of characters of s
sort(chars)
return join(chars)
}
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
}
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
}
30
Write a program to find a substring within a string. If found display its starting
position
function reverseWords(s) {
words = split(s, " ")
reverse(words)
return join(words, " ")
}
31