# All posts tagged algorithms

Problem statement Given an array of values, design and code an algorithm that returns whether there are two duplicates within indices of each other? Do all, in running time and space. Solution The main idea is to always carry the last -visited elements with each iteration. public class FindDuplicateWithinN { . . . Read more

Problem statement Logan is cleaning his apartment. In particular, he must sort his old favorite sequence, , of positive integers in nondecreasing order. He’s tired from a long day, so he invented an easy way (in his opinion) to do this job. His algorithm can be described by the following . . . Read more

Problem statement Write a program that takes an array denoting the daily stock price, and returns the maximum profit that could be made by buying and then selling one share of stock. Solution public class BuySellStockOnce { public static int solve(int[] stockPrice) { int minimumSeenSoFar = stockPrice[0]; int[] maxProfit = . . . Read more

Problem statement You are given a square map of size . Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent . . . Read more

Problem statement Two people are playing game of Misère Nim. The basic rules for this game are as follows: The game starts with piles of stones indexed from to . Each pile (where ) has stones. The players move in alternating turns. During each move, the current player must remove . . . Read more

Problem statement Given a word , consisting of characters a-z, A-Z and 0-9, compute the next lexicographical word , with 0-9 < A-Z < a-z. Sample Input hLPk7 Output hLPk8 Solution import sys def nextWord(w): word = list(w) cursor = len(w) – 1 carry = True while carry and cursor . . . Read more

Problem statement Given sticks of lengths , use of the sticks to construct a non-degenerate triangle with the maximum possible perimeter. Then print the lengths of its sides as space-separated integers in non-decreasing order. If there are several valid triangles having the maximum perimeter: Choose the one with the longest . . . Read more

Problem statement Given two strings and of equal length, what’s the longest string () that can be constructed such that it is a child of both? A string is said to be a child of a string if can be formed by deleting or more characters from . For example, . . . Read more

This is a rather short post. in which I explain how to we can implement a fast pow function to raise a number to the power of . A rather naive approach would be to do the following: int pow(int x, int n){ int result = 1; while (n > . . . Read more

Problem statement You are situated in an dimensional grid at position . The dimensions of the grid are In one step, you can walk one step ahead or behind in any one of the dimensions. (So there are always possible different moves). In how many ways can you take steps . . . Read more