Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

Dedup LinkedList

Write code to remove duplicates from an unsorted linked list

FOLLOW UPHow would you solve this problem if a temporary buffer is not allowed

trait Node {
  def value: Int
  def next: Node
}

object Empty extends Node {
  def value: Int = throw new Error("access empty variable")
  def next: Node = throw new Error("access empty variable")
}

case class NonEmpty(value: Int, next: Node = null) extends Node

def toLinkedList(lst: List[Int]): Node = {
  if (lst.isEmpty) Empty
  else new NonEmpty(lst.head, toLinkedList(lst.tail))
}

def printLinkedList(head: Node): Unit = head match {
  case Empty =>
  case node: NonEmpty => {
    println(node.value)
    printLinkedList(node.next)
  }
}

/**
  * 2.1
  *
  * @param head
  * @return
  */
def deduplicate(head: Node): Node = {
  val dict = scala.collection.mutable.Map[Int, Boolean]()
  def dedup(node: Node): Node = {
    node match {
      case Empty => Empty
      case current: NonEmpty => {
        dict.get(current.value) match {
          case Some(value) => dedup(current.next)
          case None => {
            dict += (current.value -> true)
            new NonEmpty(current.value, dedup(current.next))
          }
        }
      }
    }
  }
  dedup(head)
}

var node = toLinkedList(List(1, 2, 3, 4, 4, 5, 6, 6))
printLinkedList(deduplicate(node))

Previousk-th element to last of a LinkedListNextCheck Rotated String

Last updated 6 years ago