Skip to main content

Posts

Showing posts with the label data structures

Daily Coding Problem: Find the majority element in an array

My solution to a “Daily Coding Problem” that I received in my mail today. Given a list of elements, find the majority element, which appears more than half the time ( > floor(len(lst) / 2.0) ). You can assume that such element exists. For example, given  [1, 2, 1, 1, 3, 4, 0] , return 1. Here’s my solution in, oneFiftyFive(arr: number[]):number { if (arr == null || arr == undefined) { return 0; } let half = Math.floor(arr.length / 2); //find max occurance let occurenceMap = new Map<number, number>(); let maxOccurence = 0; for(let i = 0; i < arr.length; i++) { let n = arr[i]; if(occurenceMap.has(n)) { let val = occurenceMap.get(n) + 1; //we get out the moment we find the max occurence //what if 2 numbers have the same frequency of occurence? if(val >= half) { maxOccurence = val; break; } occurenceMap.set(n, val); } else { occurenceMap.set(n, 1); } } return max...

Queue, Binary Tree and BFS in iOS Swift

Following on from my last post, this is a short post with code samples to achieve the above on Swift. I won’t talk too much about the background to Binary Search Trees or the BFS algorithm, instead just focus on the code. If you need to get more of a background to this post, then best have a read of my previous post,  Breadth-First Search in Typescript and Javascript. The code Just like my  previous post , this code solves the exact same problem, except here it’s done in Swift instead of Typescript or Javascript. class Node<T: Comparable> { var key: T! var left: Node? var right: Node? init(key:T) { self.key = key } } class Queue<T> { private var items = [T]() func add(item: T) { items.append(item) } func pop() -> T? { return items.removeFirst() } func isEmpty() -> Bool { return (items.count == 0) } } class BinaryTree<H:Comparable> { private var rootNode: Node...