Questions tagged [algorithm]

An algorithm is a sequence of well-defined steps that defines an abstract solution to a problem. Use this tag when your issue is related to algorithm design.

algorithm
Filter by
Sorted by
Tagged with
4929 votes
62 answers
3.6m views

How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i < a.length; i++...
brad's user avatar
  • 74.8k
5373 votes
43 answers
831k views

What is a plain English explanation of "Big O" notation?

I'd prefer as little formal definition as possible and simple mathematics.
Arec Barrwin's user avatar
  • 61.8k
1676 votes
22 answers
297k views

What is the best algorithm for overriding GetHashCode?

In .NET, the GetHashCode method is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when ...
bitbonk's user avatar
  • 49.2k
978 votes
24 answers
536k views

Big O, how do you calculate/approximate it?

Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how well an algorithm scales. But I'm curious, how do you calculate or approximate the complexity of ...
sven's user avatar
  • 18.3k
1468 votes
58 answers
2.2m views

Removing duplicates in lists

How can I check if a list has any duplicates and return a new list without duplicates?
Neemaximo's user avatar
  • 20.5k
1039 votes
10 answers
879k views

How can I find the time complexity of an algorithm?

I have gone through Google and Stack Overflow search, but nowhere I was able to find a clear and straightforward explanation for how to calculate time complexity. What do I know already? Say for code ...
Yasser Shaikh's user avatar
853 votes
41 answers
1.1m views

How do I generate all permutations of a list?

How do I generate all the permutations of a list? For example: permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, ...
Ricardo Reyes's user avatar
1013 votes
66 answers
648k views

Count the number of set bits in a 32-bit integer

8 bits representing the number 7 look like this: 00000111 Three bits are set. What are the algorithms to determine the number of set bits in a 32-bit integer?
1160 votes
49 answers
1.2m views

Calculate distance between two latitude-longitude points? (Haversine formula)

How do I calculate the distance between two points specified by latitude and longitude? For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to ...
Robin Minto's user avatar
  • 15.2k
661 votes
32 answers
651k views

How do you compare float and double while accounting for precision loss?

What would be the most efficient way to compare two double or two float values? Simply doing this is not correct: bool CompareDoubles1 (double A, double B) { return A == B; } But something like: ...
Alex's user avatar
  • 6,651
645 votes
77 answers
559k views

Algorithm to return all combinations of k elements from n

I want to write a function that takes an array of letters as an argument and a number of those letters to select. Say you provide an array of 8 letters and want to select 3 letters from that. Then ...
576 votes
15 answers
140k views

What is the most efficient/elegant way to parse a flat table into a tree?

Assume you have a flat table that stores an ordered tree hierarchy: Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 ...
Tomalak's user avatar
  • 335k
217 votes
30 answers
187k views

Rolling or sliding window iterator?

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. (Default Python iteration could be considered a special case, where the window length is 1.) I'm currently ...
David B.'s user avatar
  • 5,770
179 votes
36 answers
88k views

Cartesian product of multiple arrays in JavaScript

How would you implement the Cartesian product of multiple arrays in JavaScript? As an example, cartesian([1, 2], [10, 20], [100, 200, 300]) should return [ [1, 10, 100], [1, 10, 200], [1, ...
viebel's user avatar
  • 20k
2052 votes
29 answers
612k views

What is tail recursion?

Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?
311 votes
32 answers
625k views

Finding all possible combinations of numbers to reach a given sum

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number? A brief example: Set of numbers to add: N = {1,5,22,15,0,.....
James P.'s user avatar
  • 19.5k
1103 votes
10 answers
294k views

What is tail call optimization?

Very simply, what is tail-call optimization? More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?
majelbstoat's user avatar
  • 13.2k
197 votes
23 answers
119k views

Unique (non-repeating) random numbers in O(1)?

I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is ...
dicroce's user avatar
  • 46k
236 votes
20 answers
93k views

Understanding recursion [closed]

I'm having major trouble understanding recursion at school. Whenever the professor is talking about it, I seem to get it but as soon as I try it on my own it completely blows my brains. I was trying ...
Confused's user avatar
  • 2,393
462 votes
57 answers
694k views

Generating all permutations of a given string

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?
GurdeepS's user avatar
  • 66.2k
312 votes
20 answers
278k views

The most efficient way to implement an integer based power function pow(int, int)

What is the most efficient way given to raise an integer to the power of another integer in C? // 2^3 pow(2,3) == 8 // 5^5 pow(5,5) == 3125
Doug T.'s user avatar
  • 64.9k
217 votes
18 answers
258k views

Fastest way to flatten / un-flatten nested JavaScript objects

I threw some code together to flatten and un-flatten complex/nested JavaScript objects. It works, but it's a bit slow (triggers the 'long script' warning). For the flattened names I want "." ...
Louis Ricci's user avatar
574 votes
53 answers
1.0m views

Best way to reverse a string

I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this: public string Reverse(string text) { char[] cArray = text.ToCharArray(); string ...
Guy's user avatar
  • 66.1k
179 votes
13 answers
55k views

Is using Random and OrderBy a good shuffle algorithm? [closed]

I have read an article about various shuffle algorithms over at Coding Horror. I have seen that somewhere people have done this to shuffle a list: var r = new Random(); var shuffled = ordered.OrderBy(...
Svish's user avatar
  • 155k
347 votes
2 answers
36k views

How to implement classic sorting algorithms in modern C++?

The std::sort algorithm (and its cousins std::partial_sort and std::nth_element) from the C++ Standard Library is in most implementations a complicated and hybrid amalgamation of more elementary ...
TemplateRex's user avatar
  • 69.9k
447 votes
12 answers
357k views

Image comparison - fast algorithm

I'm looking to create a base table of images and then compare any new images against that to determine if the new image is an exact (or close) duplicate of the base. For example: if you want to ...
meade's user avatar
  • 23k
341 votes
25 answers
374k views

How to determine if a point is in a 2D triangle? [closed]

What is the simplest algorithm to determine if a point is inside a 2d triangle?
ET 0.618's user avatar
  • 3,493
558 votes
13 answers
230k views

Why do we check up to the square root of a number to determine if the number is prime?

To test whether a number is prime or not, why do we have to test whether it is divisible only up to the square root of that number?
Pan's user avatar
  • 6,525
235 votes
32 answers
251k views

How to find the kth largest element in an unsorted array of length n in O(n)?

I believe there's a way to find the kth largest element in an unsorted array of length n in O(n). Or perhaps it's "expected" O(n) or something. How can we do this?
MrDatabase's user avatar
2733 votes
32 answers
1.6m views

What does O(log n) mean exactly?

I am learning about Big O Notation running times and amortized times. I understand the notion of O(n) linear time, meaning that the size of the input affects the growth of the algorithm ...
Andreas Grech's user avatar
191 votes
21 answers
219k views

Best way to randomize an array with .NET

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new Array with the same strings but in a random order. Please include a C#...
Mats's user avatar
  • 15.1k
161 votes
30 answers
286k views

How to create the most compact mapping n → isprime(n) up to a limit N?

Naturally, for bool isprime(number) there would be a data structure I could query. I define the best algorithm, to be the algorithm that produces a data structure with lowest memory consumption for ...
Khaled Alshaya's user avatar
251 votes
24 answers
244k views

HSL to RGB color conversion

I am looking for an algorithm to convert between HSL color to RGB. It seems to me that HSL is not very widely used so I am not having much luck searching for a converter.
hhafez's user avatar
  • 39.3k
164 votes
34 answers
209k views

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of the farthest left bit that ...
Zxaos's user avatar
  • 7,941
18 votes
3 answers
7k views

Fast bignum square computation

To speed up my bignum divisons I need to speed up operation y = x^2 for bigints which are represented as dynamic arrays of unsigned DWORDs. To be clear: DWORD x[n+1] = { LSW, ......, MSW }; where n+1 ...
526 votes
8 answers
130k views

What is Constant Amortized Time?

What is meant by "Constant Amortized Time" when talking about time complexity of an algorithm?
VarunGupta's user avatar
  • 6,207
197 votes
29 answers
230k views

Listing all permutations of a string/integer

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation. Is there an example of how this is done ...
GurdeepS's user avatar
  • 66.2k
298 votes
10 answers
200k views

How to sort in-place using the merge sort algorithm?

I know the question is not too specific. All I want is someone to tell me how to convert a normal merge sort into an in-place merge sort (or a merge sort with constant extra space overhead). All I ...
Lazer's user avatar
  • 92.4k
584 votes
13 answers
185k views

Why does Java's hashCode() in String use 31 as a multiplier?

Per the Java documentation, the hash code for a String object is computed as: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string,...
jacobko's user avatar
  • 8,860
724 votes
31 answers
393k views

How to check if a number is a power of 2

Today I needed a simple algorithm for checking if a number is a power of 2. The algorithm needs to be: Simple Correct for any ulong value. I came up with this simple algorithm: private bool ...
configurator's user avatar
  • 41.2k
450 votes
10 answers
292k views

What is stability in sorting algorithms and why is it important?

I'm very curious, why stability is or is not important in sorting algorithms?
DarthVader's user avatar
  • 54.1k
244 votes
29 answers
151k views

Detecting endianness programmatically in a C++ program

Is there a programmatic way to detect whether or not you are on a big-endian or little-endian architecture? I need to be able to write code that will execute on an Intel or PPC system and use exactly ...
Jay T's user avatar
  • 2,449
461 votes
14 answers
405k views

Which cycle detection within a directed graph are more efficient than O(n^2)? [closed]

Is there an algorithm that is more time efficient than O(n^2) for detecting cycles within a directed graph? I have a directed graph representing a schedule of jobs that need to be executed, a job ...
Peauters's user avatar
  • 4,873
877 votes
19 answers
497k views

How can building a heap be O(n) time complexity?

Can someone help explain how can building a heap be O(n) complexity? Inserting an item into a heap is O(log n), and the insert is repeated n/2 times (the remainder are leaves, and can't violate the ...
GBa's user avatar
  • 17.8k
365 votes
64 answers
407k views

How do you rotate a two dimensional array?

Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world ...
88 votes
25 answers
97k views

Sort on a string that may contain a number

I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the ...
Paul Tomblin's user avatar
130 votes
38 answers
191k views

Counting inversions in an array

I'm designing an algorithm to do the following: Given array A[1... n], for every i < j, find all inversion pairs such that A[i] > A[j]. I'm using merge sort and copying array A to array B and ...
el diablo's user avatar
  • 2,687
267 votes
28 answers
268k views

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

What is the most efficient algorithm to achieve the following: 0010 0000 => 0000 0100 The conversion is from MSB->LSB to LSB->MSB. All bits must be reversed; that is, this is not endianness-...
green_t's user avatar
  • 3,007
565 votes
32 answers
628k views

Check if all elements in a list are identical

I need a function which takes in a list and outputs True if all elements in the input list evaluate as equal to each other using the standard equality operator and False otherwise. I feel it would be ...
max's user avatar
  • 50.7k
407 votes
21 answers
349k views

Determine if two rectangles overlap each other?

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to ...
Rob Burke's user avatar
  • 5,435

1
2 3 4 5
268