kimc0de
Hi all, I’m trying to solve this leetcode question in elixir. https://leetcode.com/problems/contains-duplicate-ii/
Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k .
The java solution is available but it was quite complicated for me to convert to elixir.. Could anyone give me some hints or explanations on how to solve it in elixir?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
lud
In elixir you can pattern match on a list:
Then, you would use recursion to traverse the whole list.
Does it help?
viniarck
You could group values by their indexes and for each grouped values, recursively iterate with a look ahead pointer on a list that has at least two elements comparing if the indexes abs diff is <= k, if you do all of this lazily and then try to take at least 1 and if it’s not an empty list then you’ve found one pair of indexes.
I think something like this would do it:
Eiji
Isn’t your solution a bit complicated?
Based on your example I wrote my own solution using pattern-matching,
[head | tail]notation and recursion as suggested by @lud. Since all checks are guard and the list is iterated only once my version should be much more faster.First of all we can add index and perform all checks in one call. Secondly we do not need to store old index that failed our checks. Only noticing it allows us to much reduce out code.
Helpful resources:
al2o3cr
One approach I’ve found useful for problems like this is to look at the requirements:
A tool that matches these requirements is
Enum.reduce_while/3, a skeleton of a use for it would look something like:The bits in all-caps are going to vary based on the problem, but this is the general idea. The final
casehandles the situation when thereduce_whilemakes it to the end and returns whatever shape the “state” is.A simple example for using this approach is “Contains Duplicate” (the prequel to “Contains Duplicate II”). A solution for that might look like:
In this case the “state” is a single
MapSet, allowing for quick checking of “is this newnumone that’s already been seen?”For “Contains Duplicate II”, the set of “seen” elements needs to be restricted to a maximum size
k. When ak+1th element is seen, the oldest one needs to be dropped.This isn’t possible with
MapSetalone; it does not provide guarantees about element ordering. To handle it, we need a second piece of “state”: a queue of numbers that can answer “what element did we seekelements ago?” efficiently.The
:queuemodule is a decent starting point with better performance characteristics than a plain List when values are removed from the opposite end.Another useful piece of information: the size of a MapSet is efficiently computable, especially compared to
:queue.lenwhich isO(k).A solution for part 2 might look like (I have not run this code, beware):
The
ifin the skeleton has split into a 3-waycond:numis inseen, we’re done hereseenis smaller than the maximum, recordnumand go onto the next oneseenand carry onI’d likely extract parts of this to a function, but I kept everything inline for this discussion to show the similarities.
gregvaughn
Perhaps not the most efficient, but quite straightforward
evadne
to my eyes, this is O(n^2)
kimc0de
This solution doesn’t pass all cases, unfortunately..
false = ([1,2,3,1], 3) → supposed to be true
false = ([1,0,1,1], 1) → supposed to be true
false = Test.test([1,2,3,1,2,3], 2) → correct
kimc0de
Thank you for the detailed explanation. This solution works with some minor syntax adjustment.
kimc0de
I like this suggestion, works just fine and is quite easy for me to understand. Thanks for the resources.
gregvaughn
Ah, a classic “fencepost” error. The original problem was specified with indicies and I solved for count. Simple fix: use
k+1where I previously usedk