1,530 questions
3
votes
2
answers
165
views
Use of !! in memoization
When looking up memoization in Haskell, I found this bit of code:
memoized_fib :: Int -> Integer
memoized_fib = (map fib [0 ..] !!)
where fib 0 = 0
fib 1 = 1
fib n = ...
0
votes
1
answer
154
views
Memoize function repeatedly called with same arguments?
I have a mathematical function called in render loop (240Hz). It's a function of some (atomic) state that very rarely changes. It calls 3 times to std::log, twice to std::sqrt, once to std::sin.
When ...
0
votes
0
answers
55
views
Valid Parenthesis String, Recursion with memoization to DP
How can the following recursion + memoization code be converted into a tabulation format dynamic programming solution?
The code is working but I want to improve it.
The challenge I am facing is ...
0
votes
2
answers
89
views
Flattening an array causes UI freeze
I have an app with cards. Cards are fetched with useInfiniteQuery from React Query. I fetch new card each time I reach the end of the list.
Backend sends offset and limit based responses of this ...
2
votes
2
answers
102
views
How to avoid re-render in Redux based on the outputs of .filter()?
I have a simple scenario in which I want to access my store.entities, but only those which are active. I understand the following is bad because a new reference is given each time:
const ...
0
votes
0
answers
26
views
I'm using this memoized dropdown component, which seems to close due to a re-render when the child text input box component inside changes
I'm stuck on this problem where I memoized the Dropdown component because it was causing infinite re-renders when I selected something from the dropdown. Now I'm facing an issue where everytime I ...
0
votes
1
answer
105
views
Storing the recursive call result in a variable leads to incorrect calculation in a DP memoized solution
Just by using the commented code instead of making the recursive calls inside the max function, leads to incorrect result particularly with the following test case
int main() {
Solution obj = ...
1
vote
2
answers
163
views
What is the time complexity of the following algorithm and is there any optimization I can do?
Problem: Given an array that sums to 0, find the maximum number of partitions of it such that all of them sum up to 0 individually.
Example:
input: [-2, 4, -3, 5, -4]
output: 2 (which are [[5, -2, -3]...
1
vote
1
answer
102
views
How can I memoize a JavaScript function that accepts multiple arguments, including objects?
I’m trying to improve the performance of a computationally expensive JavaScript function by memoizing it. The function accepts multiple arguments, including objects. Here's an example:
function ...
0
votes
1
answer
154
views
Why is this DFS + Memoization solution for selecting indices in two arrays too slow while a similar approach is more efficient?
I was solving LeetCode problem 3290. Maximum Multiplication Score:
You are given an integer array a of size 4 and another integer array b of size at least 4.
You need to choose 4 indices i0, i1, i2, ...
0
votes
1
answer
58
views
3-D DP VS 2-D DP, can't seem to figure out why my code can't be memoized
class Solution {
public:
int countNeighborhoods(const vector<int>& houses) {
int neighborhoods = 0;
int m = houses.size();
for (int i = 0; i < m; i++) {
...
2
votes
0
answers
131
views
Function memoization, passing around precomputed values [closed]
I have a function like this in my library, which depends on a large subset of the inputs being pre-calculated:
@cache
def f(n, precompute):
if n < len(precompute):
return precompute[n]
...
-3
votes
1
answer
129
views
Adding DP to 0/1 knapsack
Here are the two different ways of solving 0/1 knapsack using recursion.
#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define vb vector<bool>
long long solve1(...
3
votes
0
answers
66
views
Why does my recursive memoization function cause a 'Maximum Call Stack Exceeded' error in JavaScript?
While solving fabonocci problem using recursion and memoization in JavaScript, I got "Maximum Call Stack Exceeded" error when I try to run it with large inputs. To troubleshoot, I copied the ...
0
votes
1
answer
56
views
createSelector difference for the memoization values
I have the following problem , in the code I found many places where the createSelector was not implemented correctly and i want to change it to imporve performance in the frontend.
Originally the ...
0
votes
1
answer
182
views
How to cache a mutable instance attribute?
I can cache an instance attribute like so:
from dataclasses import dataclass
from functools import cached_property
@dataclass
class Point:
_x: float
@cached_property
def x(self):
...
2
votes
3
answers
159
views
Is there a way initialize a matrix(2D array) with some default values(-1)
I was going through a dp problem, there I have to initialize the matrix with default(-1) values for memoized solution. And felt the need.
We can initialize the 1D array in java like this => Arrays....
0
votes
2
answers
327
views
Dynamic Programming - Minimum cost to fill given weight in a bag
We are given an array of positive weights cost where cost[i] represents the cost of filling i + 1 kg's of oranges in a bag (0-based indexing). We need to find the minimum cost to buy exactly w kg's of ...
1
vote
1
answer
41
views
How do i add memoization when calculating longest subsequence for an integer array?
I'm doing https://leetcode.com/problems/longest-increasing-subsequence/
I know in theory that each index needs to be assigned a length but i'm having trouble coding it up using my iterative approach
/*...
1
vote
1
answer
42
views
How can ConditionalWeakTable be used with multiple references?
ConditionalWeakTable represents a thread-safe way to attach references to other references and not have to worry about garbage collection of the attached references. However, it can only be used with ...
0
votes
0
answers
35
views
Caching using SpatialFocus.MethodCache but with Static Methods in C#
I am trying to use SpatialFocus.MethodCache but with a static method rather than in an instance of a class. I am getting an error:
1>MSBUILD : warning : Fody/SpatialFocus.MethodCache: Class Test ...
0
votes
1
answer
116
views
Defining Elements outside of component
I wonder if it OK to define the Elements outside of the components. Just something like this
const Element = <Component/>
const App = () => {
return <MemoizedParentComponent>{Element}&...
0
votes
0
answers
153
views
React useState and useMemo not preserving state during client-side routing
I'm encountering an issue with preserving state in a React component when client-side routing occurs. Specifically, I'm using the useState and useMemo hooks to manage and memoize the state of sorted ...
0
votes
0
answers
159
views
ZIO#memoize inside a service
I am designing a ZIO service. And I have to use memoization in it's internal logic. How can I do that?
For example, if a method (or all the methods) of a service require some kind of authorization ...
0
votes
1
answer
387
views
Good "hash_func" for unhashable items in streamlit's st.cache_resource - mainly dataframes?
Streamlit's st.cache_resource decorator is key to speeding up streamlit apps.
In functions like:
@st.cache_resource
def slow_function(inputA, input_b):
...
return something
it can speed up the ...
0
votes
2
answers
54
views
Array received as prop from parent used as a dependency of useMemo triggers infinite re-rendering
I have a component that looks like this
import { useState, useEffect, useMemo } from 'react'
import Input from '~/components/Input'
import Fuse from 'fuse.js'
interface Props {
data: any[]
keys: ...
1
vote
1
answer
124
views
Quickly memoize anonymous recursive functions using lambdas and the "fix function"
Background
I recently learned that the fixed-point combinator makes it easy to define recursive functions without naming them.
It is primarily used in functional programming languages (e.g. fix ...
-2
votes
1
answer
80
views
How does the useCallback() hook solve function equality issues in React?
Introduction
I'm trying to understand the useCallback() hook in React and its role in solving function equality issues. I came across a blog post that discusses this concept, but I'm still unclear ...
0
votes
2
answers
65
views
Unnecessary Rerender Using Memo React
i am trying to understand react memo and i created a simple interface in my react native app. the app consists of two elements:
MainApp.tsx -> controls the list of the user
User.tsx -> displays ...
0
votes
0
answers
20
views
Console.log is giving a weird result when using closure, recursion, and memoization? (simple factorial func) [duplicate]
const memoFactorial = () => {
let cache = { 1: 1 }
return function factorial(n) {
console.log(cache)
if (n in cache) {
console.log('Fetching from cache:', n)
return cache[n]
...
0
votes
1
answer
43
views
Unexpected memoization in functions
My case is very straightforward - everyone has this kind of hooks.
It contains state and returns some method for operating this state.
My question is why I sometimes get state variable (loadedPolys) ...
0
votes
1
answer
85
views
How is it possible to memoize longest divisible subset using only the length (and end position)?
The goal is to find the largest divisible subset. A divisible subset is a subset s.t. for every pair of elements i, j, either i is divisible by j or j is divisible by i. The general approach to solve ...
2
votes
0
answers
280
views
Wrapping component can avoid child component re-rendering...?
I saw one posting that is about 'how to prevent rerendering, and too much adding memoization'.
The posting: https://d2.naver.com/helloworld/9223303
(it's written in korean, I'm not sure it has english ...
2
votes
1
answer
83
views
Issue with Memoization in Recursive Function for Finding Combinations Summing to Target
I need to write the following function:
Write a function that takes in a target (int) and a list of ints. The function should return a list of any combination of elements that add up to the target, ...
1
vote
1
answer
343
views
Test that a memoized component is not rerendered
In my last commit, I degraded the performance of my React app (I introduced Context, and I learned that it interfers with Memoization).
I would like to add tests that checks that a memoized component ...
1
vote
1
answer
50
views
Can recycling python object ids be a problem to a Pickler?
I read that pyhton will recycle IDs, meaning that a new object can end up with the ID of one that previously existed and was distroyed. I also read about pickle:
The pickle module keeps track of the ...
1
vote
1
answer
683
views
difference between useMemo and cache in react
In React we have latest new function called cache so what should be different between cache and useMemo hook in react
import {cache} from 'react';
0
votes
0
answers
65
views
Why memoization is not speeding up recursive problem of converting integers to Words
I am using following code to optimize the speed of the overall program execution. This program execution involves memoization. ( i.e. I am maintaining the results in an existing dictionary and using ...
0
votes
0
answers
143
views
Minimum Cost Path Recursion - Memoization
Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which ...
1
vote
1
answer
1k
views
Why Is It Called Memoization?
Memoization is a programming technique where the results of expensive function calls are stored and reused, preventing redundant computations and improving performance.
Sample Memoization
import java....
0
votes
1
answer
293
views
LeetCode - Minimum Falling Path Sum - question on memoization
I am trying to solve this leetcode problem: https://leetcode.com/problems/minimum-falling-path-sum/description
Given an n x n array of integers matrix, return the minimum sum of any falling path ...
2
votes
1
answer
523
views
Can I tag data access for manual cache revalidation without using fetch with Next app router?
I would like to implement a revalidation endpoint in a Next project with the app router, so I think my options would be revalidatePath and revalidateTag.
The data access I want revalidated works with ...
1
vote
1
answer
2k
views
How to mock a memoized React component with Jest
I want to mock a React component that has been memoized. I'm using React 18.2 and Jest 29.7 with Typescript, in case that matters. I've tried several things but can't seem to find a way that works.
...
1
vote
2
answers
145
views
how to store a vector as key of a map [duplicate]
I want to memoize the return result of my function that take two int. i know i could convert the vector as a string like 1-2 but is there another way to do it ?
I tried to set an array as a map but ...
1
vote
0
answers
85
views
Why is this solution to Knight probability in chessboard wrong?
The problem statement from leetcode - https://leetcode.com/problems/knight-probability-in-chessboard/
Basically, knight starts from a given position and randomly picks 1 of 8 possible moves. It makes ...
0
votes
0
answers
18
views
Defining a None matrix in python through different methods obtains different results [duplicate]
I have the following python code,
def helper(nums, d, n, memo):
if d == 0:
return True
if (d < 0 or n == 0):
return False
if memo[n][d] is not None:
return memo[...
1
vote
2
answers
122
views
How can I precompute constants for frozen random variable in SciPy?
I have defined a custom continuous distribution, with implemented _pdf and _cdf methods.
For these I need to compute expensive constants (given the parameters), namely the normalization constant for ...
1
vote
1
answer
187
views
Issue with implementation of longest common subsequence
I'm doing this challenge: https://leetcode.com/problems/longest-common-subsequence/
I've tried a number of ways to debug my code, but I can't figure out what's wrong.
Like in my head the way I ...
0
votes
0
answers
569
views
Longest Stable Subsequence - Recover solution from memo table
I am working on a DP problem to find longest stable subsequence, and I'm currently stuck with recovering the solution.
Here is the problem statement
I have tried the below solution,
def computeLSS(a):...
0
votes
1
answer
35
views
How can I use recursion and memoization to understand whether the a string is a combination of other two strings?
Consider 2 strings:
a = "wxy"
b = "mnop"
z = "wmxnoyp"
string z is a mixedstring if it is a combination of string a and b such that the length of string z is equal to ...